温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Springboot中怎么自定义全局异常处理

发布时间:2021-07-29 16:05:30 来源:亿速云 阅读:120 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关Springboot中怎么自定义全局异常处理,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

捕获全局异常:

首先呢,我们新建我们负责全局异常捕捉处理的类:MyControllerAdvice,代码如下:

@ControllerAdvicepublic class MyControllerAdvice {  @ResponseBody  @ExceptionHandler(value = Exception.class)  public Map<String,Object> exceptionHandler(Exception ex){    Map<String,Object> map = new HashMap<String,Object>();    map.put("code",100);    map.put("msg",ex.getMessage());    //这里可以加上我们其他的异常处理代码,比如日志记录,,,    return map;  }}

注解说明:@ControllerAdvice 通过AOP的方式配合@ExceptionHandler()注解捕获在Controller层面发生的异常。如果需要扫描自定路径下的Controller,添加basePackages属性

@ControllerAdvice(basePackages ="com.example.demo.controller")

@RestControllerAdvice : 和@ControllerAdvice作用相同,可以理解为 @ResponseBody+@ControllerAdvice 的组合使用。

@ExceptionHandler():该注解作用主要在于声明一个或多个类型的异常,当符合条件的Controller抛出这些异常之后将会对这些异常进行捕获,然后按照其标注的方法的逻辑进行处理,从而改变返回的视图信息。

测试:

@RestControllerpublic class UserController {  @GetMapping("/test")  public String test(){    int num = 1/0;    return "Hello World";  }}

结果:

{"msg":"/ by zero","code":100}

捕获自定义异常:

自定义我们的异常信息类MyException 并继承RuntimeException:

public class MyException extends RuntimeException {  private String errorCode;  private String errorMsg;  public MyException(String errorCode, String errorMsg) {    this.errorCode = errorCode;    this.errorMsg = errorMsg;  }  public String getErrorCode() {    return errorCode;  }  public void setErrorCode(String errorCode) {    this.errorCode = errorCode;  }  public String getErrorMsg() {    return errorMsg;  }  public void setErrorMsg(String errorMsg) {    this.errorMsg = errorMsg;  }  }

修改我们的MyControllerAdvice,将MyException添加进去:

@ResponseBody  @ExceptionHandler(value = MyException.class)  public Map<String,Object> myExceptionHandler(MyException mex){    Map<String,Object> map = new HashMap<String,Object>();    map.put("code",mex.getErrorCode());    map.put("msg",mex.getErrorMsg());    //其他业务代码...    return map;  }

测试:

@GetMapping("/test1")  public String test1(){    String name = null;    if(name == null){      throw new MyException("101","用户名为空");    }    return "Hello World";  }

输出:

{"msg":"用户名为空","code":"101"}

看完上述内容,你们对Springboot中怎么自定义全局异常处理有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI