-
Notifications
You must be signed in to change notification settings - Fork 4
Exception Handlers
hendryluk edited this page Feb 19, 2015
·
4 revisions
Reference: http://docs.jboss.org/seam/3/solder/snapshot/reference/en-US/html/part5.html
public class MyComponent
{
[ExceptionsHandled]
public object Something()
{
throw MyNotFoundException();
}
}
public virtual void OnNotFoundException(
[Handles] CaughtException<MyNotFoundException> e, MyOtherDependency otherStuff)
{
/* ... do something ... */
}
The [ExceptionHandled] attribute can also be used on properties as well as on the class level (in this case: the MyComponent class).
Cormo.Web comes with exception support as the following:
- if a web-api action throws an uncaught exception, exception-handling will be triggered. You do not need any [ExceptionHandling] attribute for this to happen.
- The module produces [CatchResource] HttpResponseMessage that you can inject, e.g. into your exception handlers. This value will be used to set/override the response of the current request.
For example:
public void OnNotFoundException(
[Handles] CaughtException<MyNotFoundException> e,
[CatchResource] HttpResponseMessage response)
{
response.StatusCode = HttpStatusCode.NotFound;
}
Or could be shorten into:
[HttpStatusCode(HttpStatusCode.NotFound)]
public virtual void OnNotFoundException([Handles] CaughtException<MyNotFoundException> e)
{
}
Then you can throw that exception (MyNotFoundException) from anywhere within your application, and the framework will return 404 (NotFound) response.
The latter approach is a great way to create declaratively map exception types with http status codes, i.e. by having an exception-mapping class that contains a bunch of these declarative exception-handler methods.
Generics and constraint resolutions are also supported. E.g.:
public void OnInvalidEntities<T>(
[HandlesException] InvalidEntityException<T> e,
IRepository<T> repo) // <- whatever additional dependencies
where T: IAuditable // <- constraints
{
/* handles */
}