-
Notifications
You must be signed in to change notification settings - Fork 88
guide exception handling
For handling exceptions within a Spring application, devon4j provides the devon4j-rest module, which provides a RestServiceExceptionFacade
to handle all exceptions in a consistent way. Since the module is not suitable for Quarkus, we need to implement this ourselves.
This guide shows how to do just that. For an example, see our Quarkus reference application.
We suggest to implement the exception handling the JAX-RS way using ExceptionMapper<T>
.
RESTEasy provides several exception mappers out of the box. For example, RESTEasy’s NotFoundExceptionMapper
provides a web page that shows all available endpoints in dev mode.
Even though this looks really nice, we want to have consistent exception handling throughout the application.
We create an abstract class AbstractExceptionMapper
that acts as a base class for all of the more specific exception mappers and where the response is created in a consistent manner.
You can find an example of this class here.
public abstract class AbstractExceptionMapper {
...
protected Response createResponse(int status, String errorCode, Exception exception) {
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("code", errorCode);
if (this.exposeInternalErrorDetails) {
jsonMap.put("message", getExposedErrorDetails(exception));
} else {
jsonMap.put("message", exception.getMessage());
}
jsonMap.put("uri", this.uriInfo.getPath());
jsonMap.put("uuid", UUID.randomUUID());
jsonMap.put("timestamp", ZonedDateTime.now().toString());
return Response.status(status).type(MediaType.APPLICATION_JSON).entity(jsonMap).build();
}
...
}
For the exceptions that may occur during runtime, we create an ExceptionMapper
that extends from our AbstractExceptionMapper
class. To make the class discoverable by the JAX-RS runtime, we have to annotate the class with @Provider
.
@Provider
public class NotFoundExceptionMapper extends AbstractExceptionMapper implements ExceptionMapper<NotFoundException> {
@Override
public Response toResponse(NotFoundException exception) {
...
return createResponse(Status.NOT_FOUND.getStatusCode(), exception.getClass().getSimpleName(), exception);
}
}
Note
|
Unlike the RestServiceExceptionFacade of the devon4j-rest module, we cannot use ExceptionMapper<Throwable> in Quarkus, because in this case, the exception mapper of RESTEasy would be used, since they are more specific.
|
This documentation is licensed under the Creative Commons License (Attribution-NoDerivatives 4.0 International).