SpringBoot 定义全局捕获异常类 @RestControllerAdvice 注解

Spring 3.2中,新增了@ControllerAdvice@RestControllerAdvice 注解,可以用于定义@ExceptionHandler@InitBinder@ModelAttribute

注解@ControllerAdvice的类可以拥有@ExceptionHandler, @InitBinder@ModelAttribute注解的方法, 并且这些方法会被应用到控制器类层次的所有@RequestMapping方法上

@RestControllerAdvice@ControllerAdvice 的区别就相当于 @RestController@Controller的区别

编写自定义异常类

spring boot 默认情况下会映射到 /error 进行异常处理,但是提示并不十分友好,通过自定义异常处理,提供友好展示

import lombok.Data;

/**
 * @ClassName: CustomerException
 * @Description: 自定义异常类
 * Spring 对于 RuntimeException类的异常才会进行事务回滚,所以我们一般自定义异常都继承该异常类
 * @Author mac
 * @Date 2019-06-15 21:10
 **/
@Data
class CustomerException extends RuntimeException {

    /**
     * 返回标示码
     */
    private String code;

    /**
     * 返回详细信息
     */
    private String msg;

    public CustomerException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

定义全局返回类

import lombok.Data;

/**
 * @ClassName: Result
 * @Description: 全局返回类
 * @Author mac
 * @Date 2019-06-15 21:17
 **/
@Data
public class Result {

    private String code;
    private String message;

    public Result() {}

    public Result(String code, String message) {
        this.code = code;
        this.message = message;
    }
}

定义全局捕获异常类

import com.guahao.convention.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: MyControllerAdvice
 * @Description: 全局捕获异常类
 * @Author mac
 * @Date 2019-06-15 21:20
 **/
@RestControllerAdvice
public class MyControllerAdvice {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 应用到所有@RequestMapping, 在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) { }

    /**
     * 把值绑定到Model中, 使全局@RequestMapping可以获取该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "MaLongT");
    }

    /**
     * 指定拦截异常的类型
     * 自定义浏览器请求返回状态码
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler({CustomerException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result customerException(HttpServletRequest request, CustomerException ex) {
        // false 表示异常信息不是系统类异常
        logThrowable(false, request, ex);
        return new Result(ex.getCode(), ex.getMsg());
    }

    private void logThrowable(boolean error, HttpServletRequest request, Throwable throwable) {
        if (error) {
            this.logger.error("[" + request.getMethod() + "] " + request.getRequestURI() + (StringUtils.isEmpty(request.getQueryString()) ? "" : "?" + request.getQueryString()) + " ", throwable);
        } else if (this.logger.isInfoEnabled()) {
            this.logger.info("[" + request.getMethod() + "] " + request.getRequestURI() + (StringUtils.isEmpty(request.getQueryString()) ? "" : "?" + request.getQueryString()));
        }
    }

}

测试 Controller 层访问方法

@ModelAttribute:在Model上设置的值,对于所有被@RequestMapping注解的方法中,都可以通过 @ModelAttribute("author")获取,如下:

// 使用ModelMap也是一样效果 modelMap.get("author")
@GetMapping("/test/exception")
public String test(@ModelAttribute("author") String author) {
  throw new CustomerException("500", "系统发生500异常, 编写异常罪魁祸首: " + author);
}

启动项目,浏览器或者 postman 访问localhost:8080/test/exception, 返回信息为:

{
    "code": "500",
    "message": "系统发生500异常, 编写异常作者: MaLongT"
}

你可能感兴趣的:(SpringBoot 定义全局捕获异常类 @RestControllerAdvice 注解)