Handling domain errors in the API

apiapi-designdomain-driven-designerror handlingspring

I'm working on building an API interface on-top of a domain-driven architecture.

The domain layer has a bunch of specific exception classes (i.e. NameIsRequiredException, CannotPublishDraftException, etc) that get thrown.

We want an approach to cleanly handle these different types of errors without a whole bunch of try / catch blocks in our controllers.

We thought about potentially using the name of the field in the domain layer in the API response (i.e. a custom FieldRequired exception which has a field name property). However, this breaks down since we don't expose all the fields in our API, or the API field names might not match the names of the field in the domain layer (i.e. description vs desc) – plus we're coupling the names of the fields in our API to the names of the fields in our domain model.

Another approach was to have custom exception handlers (in Spring) to return specific errors for each possible exception (which will probably require us to have very specific exceptions in our domain layer). This approach will probably work but seems like it might have overhead / possible performance issues.

Wondering if there were any other strategies to dealing with this situation.

Best Answer

There is no need for writing try-catch-Blocks all over the controller.

1) I would derive those Exceptions from a common ancestor

2) There is ExceptionHandler which catches exceptions of a certain kind and gives control to you, what to do next. In the exception, you could carry a message, which is returned, via the reponse's body.

Regarding to security concerns or leaky abstractions, I see no problem in providing in the response's body a reason like missing required field "password" or Could not publish. Document is already published.

Of ocurse you should avoid turning things inside out.