Federico Quintas Federico Quintas - 1 year ago 124
HTTP Question

HTTP Code in Java Exceptions

In a layered application, I have to define the HTTP Code of an exception using Spring Annotation @ResponseStatus.

For example:

@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal argument")
public class IllegalContentException{


It works, but I would like to know if this is a bad practice when trying to avoid breaking Single Responsiblity Pattern (in this approach the exception knows about HTTP Codes).

The question is:

  • Should HTTP Code be defined in exceptions without taking in count the layer they belong to? Should HTTP Code be defined in exceptions belonging to DAO, Service layer and/or Controllers?

Answer Source

If you don't want to put the response codes in each exception, one option is to create a centralized exception handler with a @ControllerAdvice class consisting of methods with @ExceptionHandler and @ResponseStatus annotations.

public class CentralizedExceptionHandler {

    public String handleError(IllegalContentException e) {
        return "Illegal argument";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download