0
votes

I have a more or less simple CRUD Spring MVC application with a minimum of business logic. I'm therefore kinda heavily depending on default exception handling simply by annotating my exception classes with @ResponseStatus to control status codes with just a couple of @ExceptionHandler handlers for a few special cases. Recently I've noticed that in cases where I'm depending on default handling my responses have empty bodies, as opposed to previously containing a message from the exception (custom @ExceptionHandler work properly).

I've tried looking into white-label error page but all I can find are how-tos on the customization or disabling, nothing regarding its misconfiguration or anything similar. I'm suspecting it's caused by updating to newer spring boot and/or spring cloud dependencies, but can't find anything which would explain it in release notes

I'm expecting a JSON containing the error message as opposed to the current completely empty body.

1

1 Answers

0
votes
@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler({Exception.class})
    public ResponseEntity handler1(Exception e){
        System.out.println("error occurred!");
        ResponseStatus status = AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class);
        HttpStatus res=null;
        if(status!=null){
               res=status.value()!=null?status.value():(status.code()!=null?status.code():null);
        }
        ResponseResult result = new ResponseResult();
        result.setErrorCode(res!=null?res.value():500);
        result.setMsg(e.getMessage());
        return new ResponseEntity(result,res==null?HttpStatus.INTERNAL_SERVER_ERROR:res);
    }

}
@Setter
@Getter
public class ResponseResult {
    private String msg;

    private int errorCode;
}

This way it returns JSON containing your error msg and the http response status is 500 or the status you annotated on your Exception class.