In projects, there are often some business needs to throw an Exception, but if the background directly throws a new Exception, the front end is very ugly, not friendly to the user prompt, today we will solve this problem.

Start by building a project that simulates throwing exceptions. As follows:

@RestController
public class DemoController {

    @GetMapping("test")
    public String test(a) throws Exception{
        if(true) {throw new Exception("error");
        }
        return "ok"; }}Copy the code

Use a browser request to see what the interface looks like:

@ ControllerAdvice and @ ExceptionHandler

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
        @ExceptionHandler
        @ResponseBody
        @ResponseStatus(HttpStatus.OK)
        public ResultDto globalException(HttpServletResponse response, Exception ex){
                log.info("ExceptionHandler...");
                log.info("Error code:"  + response.getStatus());
                ResultDto resultDto = new ResultDto();
                resultDto.setCode(0);
                resultDto.setMsg(ex.getMessage());
                resultDto.setData(null);
                returnresultDto; }}Copy the code

Define a generic structure that is returned to the front end

@Data
public class ResultDto {
    // Request result 0 is failure, other is success
    private int code;
    // Failed message
    private String msg;
    // The actual data returned to the front end
    private Object data;
}
Copy the code

Then we write a controller that simulates throwing an exception

@GetMapping("test1")
public String test1(a) throws Exception{
    if(true) {throw new NullPointerException("NullPointerException");
    }
    return "ok";
}

@GetMapping("test2")
public String test2(a) throws Exception{
    if(true) {throw new RuntimeException("RuntimeException");
    }
    return "ok";
}

@GetMapping("test3")
public String test3(a) throws MyException{
    if(true) {// Do not throw Exception directly, otherwise you cannot catch an Exception
        throw new MyException("MyException");
    }
    return "ok";
}
Copy the code

So let’s ask, what does Postman return

{
    "code"0."msg""NullPointerException"."data"null
}
Copy the code

In real business we usually return custom exceptions, so I’ll define my own exception and handle my own exception separately:

public class MyException extends Exception {
    public MyException(a) {
        super(a); }public MyException(String message) {
        super(message);
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
    }

    public MyException(Throwable cause) {
        super(cause);
    }

    protected MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace); }}Copy the code

Then add handling for MyException to GlobalExceptionHandler:

@ExceptionHandler(MyException.class)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ResultDto myException(HttpServletResponse response, MyException ex){
        log.info("MyExceptionHandler...");
        log.info("Error code:"  + response.getStatus());
        ResultDto resultDto = new ResultDto();
        resultDto.setCode(0);
        resultDto.setMsg(ex.getMessage());
        resultDto.setData(null);
        return resultDto;
}
Copy the code

Request http://localhost:8080/test3 what was in the output to the front

{
    "code"0."msg""MyException"."data"null
}
Copy the code

You can’t tell if it’s myException or globalException but if you look at the background log output you can see it clearly. So springBoot takes precedence over subclass exceptions when we handle multiple exceptions.

More original Java reading: javawu.com