Springboot全局異常處理GlobalExceptionHandler

全局異常處理

自定義異常

在應用開發過程當中,除系統自身的異常外,不一樣業務場景中用到的異常也不同,爲了與標題 輕鬆搞定全局異常 更加的貼切,定義個本身的異常,看看如何捕獲…java

package com.baizhi.exception;

public class CustomException extends RuntimeException {

    private static final long serialVersionUID = 4564124491192825748L;

    private int code;

    public CustomException() {
        super();
    }

    public CustomException(int code, String message) {
        super(message);
        this.setCode(code);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}
複製代碼

異常信息模板web

定義返回的異常信息的格式,這樣異常信息風格更爲統一spring

public class ErrorResponseEntity {

    private int code;
    private String message;
    // 省略 get set
}
複製代碼

異常處理(關鍵)

註解概述bash

  • @ControllerAdvice 捕獲 Controller 層拋出的異常,若是添加 @ResponseBody 返回信息則爲JSON格式。
  • @RestControllerAdvice 至關於 @ControllerAdvice@ResponseBody 的結合體。
  • @ExceptionHandler 統一處理一種類的異常,減小代碼重複率,下降複雜度。

建立一個 GlobalExceptionHandler 類,並添加上 @RestControllerAdvice 註解就能夠定義出異常通知類了,而後在定義的方法中添加上 @ExceptionHandler 便可實現異常的捕捉…mvc

package com.baizhi.controller;
import com.baizhi.exception.CustomException;
import com.baizhi.exception.ErrorResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {


    /**
     * 定義要捕獲的異常 能夠多個 @ExceptionHandler({})
     *
     * @param request  request
     * @param e        exception
     * @param response response
     * @return 響應結果
     */
    @ExceptionHandler(CustomException.class)
    public ErrorResponseEntity customExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        CustomException exception = (CustomException) e;
        return new ErrorResponseEntity(exception.getCode(), exception.getMessage());
    }

    /**
     * 捕獲  RuntimeException 異常
     * TODO  若是你以爲在一個 exceptionHandler 經過  if (e instanceof xxxException) 太麻煩
     * TODO  那麼你還能夠本身寫多個不一樣的 exceptionHandler 處理不一樣異常
     *
     * @param request  request
     * @param e        exception
     * @param response response
     * @return 響應結果
     */
    @ExceptionHandler(RuntimeException.class)
    public ErrorResponseEntity runtimeExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        RuntimeException exception = (RuntimeException) e;
        return new ErrorResponseEntity(400, exception.getMessage());
    }

    /**
     * 通用的接口映射異常處理方
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
                                                             HttpStatus status, WebRequest request) {
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            return new ResponseEntity<>(new ErrorResponseEntity(status.value(), exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status);
        }
        if (ex instanceof MethodArgumentTypeMismatchException) {
            MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
            logger.error("參數轉換失敗,方法:" + exception.getParameter().getMethod().getName() + ",參數:" + exception.getName()
                    + ",信息:" + exception.getLocalizedMessage());
            return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "參數轉換失敗"), status);
        }
        return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "參數轉換失敗"), status);
    }
}
複製代碼
相關文章
相關標籤/搜索