1. 程式人生 > >Spring Boot -- 異常處理

Spring Boot -- 異常處理

Spring Boot -- 異常處理

預設的異常處理

預設的異常處理有兩種方式

  • BasicErrorController 方式
  • @ExceptionHandler 註解方式

在Spring boot開發中經常遇到“Whitelabel Error Page”白色標籤錯誤頁,這個頁面當spring boot中發生錯誤時的預設處理方式,返回一個error頁面,而這個頁面的格式是固定的,這個頁面有幾個變數,對映地址:/error, status=404,type=Not Found。
SpringBoot的預設錯誤處理是BasicErrorController,支援兩種格式:

  • 錯誤頁面 errorHtml
  • json響應 error

Spring Boot預設的異常處理原始碼(BasicErrorController)

@RequestMapping(
    produces = {"text/html"}
)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    HttpStatus status = this.getStatus(request);
    Map model = Collections.
unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = this.resolveErrorView(request, response, status, model); return modelAndView != null?modelAndView:new ModelAndView("error"
, model); } @RequestMapping @ResponseBody public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { Map body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = this.getStatus(request); return new ResponseEntity(body, status); }

errorHtml()返回錯誤頁面
error()json響應錯誤


自定義的異常處理

BasicErrorController 方式

繼承BasicErrorController ,並重寫errorHtml()和error()

@Controller
public class DemoErrorController extends BasicErrorController {

    public DemoErrorController(ServerProperties serverProperties){
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        response.setStatus(status.value());

        System.out.println("do DemoErrorController errorHtml ......");

        Map<String, Object> model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML));
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
        return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));

        //輸出自定義的Json格式
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("msg", body.get("message"));

        System.out.println("do DemoErrorController error ......");

        return new ResponseEntity<>(map, status);
    }
}

@ExceptionHandler 註解方式

通過AOP切面對controller進行異常植入
@ExceptionHandler的value定義的是要匹配的異常型別,這裡寫了一個總的異常Exception,可以針對某個具體的異常進行處理。

@ControllerAdvice
public class AllExceptionHandle {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView errorHtmlHandle(HttpServletRequest request, Exception e) throws Exception{
        System.out.println("do AllExceptionHandle errorHtmlHandle ......");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e);
        modelAndView.addObject("url", request.getRequestURL());
        modelAndView.setViewName("error");
        return modelAndView;
    }

    @ExceptionHandler(value = NullPointerException.class)
    public Map<String, Object> errorJsonHandle(HttpServletRequest request, Exception e) throws Exception{
        System.out.println("do AllExceptionHandle errorJsonHandle ......");
        Map<String, Object> map = new HashMap<>();
        map.put("exception", e);
        map.put("url", request.getRequestURL());
        return map;
    }
}

轉載
Spring Boot入門教程(二十一): 異常處理