hendryluk / cormo

.NET Application Framework based on Spring and Java EE CDI
MIT License
5 stars 4 forks source link

(Cormo core and Cormo.Web): Exception handling #12

Closed hendryluk closed 9 years ago

hendryluk commented 9 years ago
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:

  1. 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.
  2. 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.

hendryluk commented 9 years ago

This should also support generics and constraint resolutions. E.g.:

public void OnInvalidEntities<T>(
       [HandlesException] InvalidEntityException<T> e, 
       IRepository<T> repo) // <- whatever additional dependencies
  where T: IAuditable // <- constraints
{
    /* handles */
}

(This is not part of CDI spec or Jboss Weld, since java doesn't have true generics)

hendryluk commented 9 years ago

This has now been implemented.