SpringMVC统一处理返回异常--@ControllerAdvice

自定义一个异常

自定义若干个运行时异常,可以根据不同的错误类型定义多个

public class TestException extends RuntimeException {

    private String code;

    public TestException(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

}

自定义异常信息类

根据需求自第一字段

public class ErrorResponse {
    private String code;

    private String message;

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

    public ErrorResponse() {
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public static ErrorResponse build(String code, String message) {
        return new ErrorResponse(code, message);
    }
}

controller增强类

@ControllerAdvice表示启动项目后, 被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 @RequestMapping 注解的方法上

  1. @ExceptionHandler表示捕获指定异常,里面的参数就是指具体捕获哪种异常,如果需要,也可以直接捕获Exception
  2. @ModelAttribute表示在Model上设置的值,对于所有被 @RequestMapping 注解的方法中,都可以通过 ModelMap 获取
  3. @InitBinde表示在其执行之前初始化数据绑定器
@ControllerAdvice
public class TestAdvice {

    // 可以定义多个,用来捕获不同的异常
    @ExceptionHandler(value = {TestException.class})
    public ResponseEntity<ErrorResponse> test(HttpServletRequest request, TestException e) {
        System.out.println("log-----------" + e.getCode() + e.getMessage());
        return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(ErrorResponse.build(e.getCode(), "test exception message"));
    }

    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("name", "lalala");
    }
}

controller测试

@RestController
public class UserController {

    /**
     * 获取@ModelAttribute的方法一
     *
     * @param modelMap
     * @return
     */
    @GetMapping("/test1")
    public String test1(ModelMap modelMap) {
        return "hello springmvc test1|" + modelMap.get("name");
    }

    /**
     * 获取@ModelAttribute的方法二
     *
     * @param name
     * @return
     */
    @GetMapping("/test3")
    public String test3(@ModelAttribute("name") String name) {
        return "hello springmvc test3|" + name;
    }

    /**
     * 异常
     *
     * @param num
     * @return
     */
    @GetMapping("/test2/{num}")
    public ResponseEntity<Object> test2(@PathVariable int num) {
        if (num != 1) {
            throw new TestException("001");
        }
        return ResponseEntity.status(HttpStatus.OK).body("hello springmvc test2");
    }
}

结果

# http://localhost:8080/test3
# httpstatus:200
hello springmvc test3|lalala

# http://localhost:8080/test1
# httpstatus:200
hello springmvc test1|lalala

# http://localhost:8080/test2/1
# httpstatus:200
hello springmvc test2

# http://localhost:8080/test2/2
# httpstatus:422
{"code":"001","message":"test exception message"}

发布了37 篇原创文章 · 获赞 1 · 访问量 1047

猜你喜欢

转载自blog.csdn.net/zhuchencn/article/details/103992089