Springboot全局异常捕获

1、使用@RestControllerAdvice或@ControllerAdvice注解异常处理类;@RestControllerAdvice返回rest风格的json数据,与@ControllerAdvice加@ResponseBody效果一致。

package com.suy.actuator.advice;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class CustomizeExceptionHandler {

    @ExceptionHandler(Exception.class) //处理自定义异常类型
    ModelAndView handle(HttpServletRequest request, Throwable ex, Model model) {
        model.addAttribute("message", ex.getMessage());
        return new ModelAndView("error");
    }

}

2、当springboot项目出现异常时,默认会跳转到/error,以上方式无法捕获异常,就需要使用ErrorController

package com.suy.actuator.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class CustomizeErrorController implements ErrorController {
    @Override
    public String getErrorPath() {
        return "error";
    }

    @RequestMapping(produces = {"text/html"})
    public ModelAndView errorHtml(HttpServletRequest request, Model model) {
        HttpStatus status = this.getStatus(request);
        if (status.is4xxClientError()) {
            model.addAttribute("message", "请求异常,请确认后重新发送");
        }
        if (status.is5xxServerError()) {
            model.addAttribute("message", "服务器异常,请稍后再试");
        }
        return new ModelAndView("error");
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode);
            } catch (Exception var4) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    }
}

[参考文档] 【Spring Boot 实战】-- 码匠笔记

https://www.bilibili.com/video/av50200264/?p=42

你可能感兴趣的:(Springboot,全局异常)