SpringBoot 全局異常處理

爲何會有這篇文章

先後端分離系統,使用SpringBoot搭建後端。
但願請求結果能夠按照HttpStatus返回。
搜索了很多關於SpringBoot的全局異常處理,大部分都是返回200,再在消息體中加入code,感受這樣處理不符合規範,因此有了如下內容。html

步驟

  1. 建立異常類
  2. 建立全局異常處理
  3. 異常使用上面建立的異常類拋出

代碼

異常類 BizException
該異常類使用最簡單結構,僅有狀態碼和自定義信息,可根據本身須要拓展。java

import org.springframework.http.HttpStatus;

/**
 * 錯誤處理類
 */
public class BizException extends RuntimeException {

    private HttpStatus status;
    private String message;

    public BizException(HttpStatus status, String message) {
        super(message);
        this.status = status;
        this.message = message;
    }

    public BizException(HttpStatus status) {
        this(status, status.getReasonPhrase());
    }

    public HttpStatus getStatus() {
        return status;
    }

    @Override
    public String getMessage() {
        return message;
    }
}

全局異常處理 GlobalExceptionHandler
該類會根據拋出類型,自動進入對應處理類。web

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局異常處理
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> bizExceptionHandler(HttpServletRequest req, BizException e) {
        Map<String, Object> map = new HashMap<>();
        map.put("message", e.getMessage());
        return new ResponseEntity<>(map, e.getStatus());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> exceptionHandler(HttpServletRequest req, Exception e) {
        Map<String, Object> map = new HashMap<>();
        map.put("message", e.getMessage());
        return new ResponseEntity<>(map, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

在任意想要的地方拋出BizException異常spring

throw new BizException(HttpStatus.UNAUTHORIZED);
throw new BizException(HttpStatus.UNAUTHORIZED,"未登陸");

請求對應鏈接,能夠觀察到狀態碼已變動爲401,並附有信息
image後端

參考資料:
小白的springboot之路(十)、全局異常處理 - 大叔楊 - 博客園
小白的springboot之路(十一)、構建後臺RESTfull API
springboot自定義http反饋狀態碼 - Boblim - 博客園springboot

首發於知乎
SpringBoot 全局異常處理前後端分離

相關文章
相關標籤/搜索