Reputation: 1878
I´m come from old VB totaly new to C#. I want to build a helper function, that I can call in this way:
void fError(400, "Parameter X is missing");
or
void fError(500, "Unexpected Error occured");
This should be a "shortcut" for me: only one line to quit processing the page with my custom error messages and Standard http error codes.
This should be my "function":
private void fError(int pErrorCode, string pErrorMessage)
{
var mCode;
if (pErrorCode == 500)
{
mCode = HttpStatusCode.InternalServerError;
}
if (pErrorCode == 400)
{
mCode = HttpStatusCode.BadRequest;
}
throw new HttpResponseException(new HttpResponseMessage(mCode)
{
Content = new StringContent(pErrorMessage),
ReasonPhrase = "MyApplication Error"
});
}
Any idea how to get this work?
Upvotes: 0
Views: 51
Reputation: 1878
Got it with the second solution:
public static void fError(string pErrorMessage, int pStatusCode)
{
throw new HttpResponseException(new HttpResponseMessage
{
StatusCode = (HttpStatusCode)pStatusCode,
Content = new StringContent(pErrorMessage),
ReasonPhrase = "MyApplication Error"
});
}
Upvotes: 0
Reputation: 9499
you're almost there. your code seems to suggest you're using ASP.NET Web API. let me know if now.
you can simplify your code further by using.
private void fError(HttpStatusCode statusCode, string pErrorMessage)
{
throw new HttpResponseException(statusCode)
{
Content = new StringContent(pErrorMessage),
ReasonPhrase = "MyApplication Error"
});
}
OR, if you don't want to send HttpStatusCode types (why not?) and want to send integers
private void fError(int statusCode, string pErrorMessage)
{
throw new HttpResponseException((HttpStatusCode)statusCode)
{
Content = new StringContent(pErrorMessage),
ReasonPhrase = "MyApplication Error"
});
}
Upvotes: 1