SpringBoot: how to deal with global exception gracefully?

Before using springboot time, just know that catch the exception using try {} catch, an interface a try {} catch, which is the most common way developers exception handling, though time-tested, but will cause a problem, is a Controller below, full screen try {} catch, looking at that is not elegant, is not in line with Xiao Ming temperament, hold back for so long, Xiao Ming finally decided to implement a unified program for all exceptions process.

Development Readiness

JDK8, normal springboot project

Coding

General Exception Handling

In fact, the project Global Spring Series exception handling has long existed, but we have been busy moving bricks, rarely stop to examine the day and night and we accompanied friends. In order to fit the theme, this major global exception handler for SpringBoot be illustrated.

SpringBoot have a @ControllerAdvicecomment, use the annotation means that the open global exception capture, then we just use the method on a custom @ExceptionHandlerannotations, and type of anomaly definitions capture, for this type of exception unified process.

for example:

If we need for NullException (abnormal null pointer, Java programmers hate exceptions, no one) globally process (as shown below).

@RestControllerAdvice
public class GlobalExceptionHandler {
        /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    public BaseResponseFacade exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常!原因是:",e);
        return ResponseUtil.error(ResponseCode.ERROR);
    }
}

Ne, it's that simple. Other abnormalities may occur, it can be processed quickly handled in this way. Here we should behave very excited, but please do not be happy too early, because then, there are even more exciting things.

Custom exception handling

Customizing an exception
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @Description 自定义异常
 * @Date 2019-08-05 15:49
 * @Created by 程序员小明
 */
@Data
@AllArgsConstructor
@Accessors(chain = true)
public class BizException extends RuntimeException {
    /**
     * 错误码
     */
    protected Integer errorCode;
    /**
     * 错误信息
     */
    protected String errorMsg;
}

Obviously, this exception inherits RuntimeException, belonging to abnormal operation. Careful friend has been found, I used the plug-in Lombok, very fit today's theme, give you a brief introduction:

lombok is that one can help us simplify the tools to write java code, in particular, simplify the writing javabean, that is by way of the use of annotations, eliminating the constructor code, getter / setter code, etc., so that our class to write more concise (if use the IDE is idea, you need to install the plug-ha).

After you define too, we can deal with our custom exception handling and NullException the same way as before. Including dealing with other abnormality, it is this way. Directly attached to the code.

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public BaseResponseFacade bizExceptionHandler(HttpServletRequest req, BizException e){
        log.error("发生业务异常!原因是:{}",e.getErrorMsg());
        return ResponseUtil.error(e.getErrorCode(),e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    public BaseResponseFacade exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常!原因是:",e);
        return ResponseUtil.error(ResponseCode.ERROR);
    }


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    public BaseResponseFacade exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常!原因是:",e);
        return ResponseUtil.error(ResponseCode.INTERNAL_SERVER_ERROR);
    }
}

The entire global exception handling core is introduced above these. Here with a Demo give you an example.

@GetMapping("/test")
public BaseResponseFacade test(){
  if(true){
    throw new BizException(1,"error");
  }
  return ResponseUtil.success();
}

Request the address bar, after entering this method throws an exception, this time global exception into force, it will return information after Exception Handling

{"errorCode":1,"errorMsg":"error","data":null}

However, this entire process run through. Of course, a lot of places we can according to their actual business situation as a basis for further enriching, such as the return data can be changed to a jump to a specific page. This is not a very elegant way of playing? You have any questions, we look forward to your comments.

Guess you like

Origin www.cnblogs.com/coderxx/p/11331855.html