User36583972 posted
Hi lolzoid,
In Web API, we can use Exception filters to handle runtime errors in your Web API application. You can define a CustomExceptionFilter class like the below.
public class CustomExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
HttpStatusCode status = HttpStatusCode.InternalServerError;
String message = String.Empty;
var exceptionType = actionExecutedContext.Exception.GetType();
if (exceptionType == typeof(UnauthorizedAccessException))
{
message = "Access to the Web API is not authorized."; //you can define message by yourself
status = HttpStatusCode.Unauthorized;
}
else if (exceptionType == typeof(DivideByZeroException))
{
message = "Internal Server Error.";//you can define message by yourself
status = HttpStatusCode.InternalServerError;
}
else
{
message = "Not found.";//you can define message by yourself
status = HttpStatusCode.NotFound;
}
actionExecutedContext.Response = new HttpResponseMessage()
{
Content = new StringContent(message, System.Text.Encoding.UTF8, "text/plain"),
StatusCode = status
};
base.OnException(actionExecutedContext);
}
}
You can register your exception filters like the below.
public static void Register(HttpConfiguration config)
{
//.................
config.Filters.Add(new CustomExceptionFilter());
//..................
}
The following tutorials for your reference.
1: Exception Handling in ASP.NET Web API:
http://www.asp.net/web-api/overview/error-handling/exception-handling
2: NET Web API 2.0 Service with a Java Client:
http://www.codeproject.com/Articles/827669/NET-Web-API-Service-with-a-Java-Client
Best Regards,
Yohann Lu