• 统一异常的处理方法


    一:知识点:

    1.@RestControllerAdvice

    1. 通过@ControllerAdvice注解可以将对于控制器的全局配置放在同一个位置。
    2. 注解了@RestControllerAdvice的类的方法可以使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上。
    3. @RestControllerAdvice注解将作用在所有注解了@RequestMapping的控制器的方法上。
    4. @ExceptionHandler:用于指定异常处理方法。当与@RestControllerAdvice配合使用时,用于全局处理控制器里的异常。
    5. @InitBinder:用来设置WebDataBinder,用于自动绑定前台请求参数到Model中。
    6. @ModelAttribute:本来作用是绑定键值对到Model中,当与@ControllerAdvice配合使用时,可以让全局的@RequestMapping都能获得在此处设置的键值对

    二,异常代码展示

    1. package com.example.demo_webmvc.zeng.exception;
    2. import com.example.demo_webmvc.zeng.util.R;
    3. import org.springframework.web.bind.annotation.ExceptionHandler;
    4. import org.springframework.web.bind.annotation.RestControllerAdvice;
    5. /**
    6. * 自定义异常消息
    7. */
    8. @RestControllerAdvice
    9. public class ZengException {
    10. /**
    11. * 全局异常
    12. * @param e
    13. * @return
    14. */
    15. @ExceptionHandler(value = Exception.class)
    16. public R runimeError(Exception e){
    17. System.out.println("运行异常---"+e.getMessage());
    18. System.out.println("全局异常--执行");
    19. return R.error("全局异常--执行");
    20. }
    21. /**
    22. * 特定异常
    23. * @param e
    24. * @return
    25. */
    26. @ExceptionHandler(value = RuntimeException.class)
    27. public R runime2Error(RuntimeException e){
    28. System.out.println("运行异常---"+e.getMessage());
    29. System.out.println("特定异常--执行");
    30. return R.error("特定异常--执行");
    31. }
    32. /**
    33. * 自定义异常
    34. * @param e
    35. * @return
    36. */
    37. @ExceptionHandler(value = CustomException.class)
    38. public R runime1Error(CustomException e){
    39. System.out.println("运行异常---"+e.getMessage());
    40. System.out.println("自定义异常--执行");
    41. return R.error("自定义异常--执行");
    42. }
    43. }
    1. package com.example.demo_webmvc.zeng.exception;
    2. /**
    3. * 异常方法
    4. */
    5. public class CustomException extends Exception {
    6. /**
    7. * 自定义异常
    8. * @param message
    9. */
    10. public CustomException(Exception message) {
    11. super(message);
    12. }
    13. }
  • 相关阅读:
    Spring的执行流程与Bean的生命周期
    Visio 无边框保存png和pdf文件
    Speedoffice(excel)文档中min函数如何使用
    分布式服务的链路跟踪 Sleuth Micrometer zipkin OpenTelemetry
    科技型中小企业申报时间?
    工作汇报
    Linux编译安装dig9.18
    CDH大数据平台 18Cloudera Manager Console之hue配置ldap(markdown新版)
    面向对象-05-06-构造方法,标准的 javabean 类
    Spring IoC Container 原理解析
  • 原文地址:https://blog.csdn.net/m0_55699184/article/details/132791474