当前位置:   article > 正文

springBoot 自定义异常_soringboot 自定义exception

soringboot 自定义exception

1、异常实体类+错误code

  1. public class ErrorInfo<T> {
  2. public static final Integer OK = 0;
  3. public static final Integer ERROR = 100;
  4. private Integer code;
  5. private String messge;
  6. private String url;
  7. private T data;
  8. public Integer getCode() {
  9. return code;
  10. }
  11. public void setCode(Integer code) {
  12. this.code = code;
  13. }
  14. public String getMessge() {
  15. return messge;
  16. }
  17. public void setMessge(String messge) {
  18. this.messge = messge;
  19. }
  20. public String getUrl() {
  21. return url;
  22. }
  23. public void setUrl(String url) {
  24. this.url = url;
  25. }
  26. public T getData() {
  27. return data;
  28. }
  29. public void setData(T data) {
  30. this.data = data;
  31. }
  32. }

2、自定义异常类

  1. public class MyException extends Exception{
  2. public MyException(String message){
  3. super(message);
  4. }
  5. }

3、全局异常捕获

  1. @ControllerAdvice
  2. public class GlobalExceptionHandler {
  3. @ExceptionHandler(value = MyException.class)
  4. @ResponseBody
  5. public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req,MyException e){
  6. ErrorInfo<String> errorInfo = new ErrorInfo<>();
  7. errorInfo.setCode(ErrorInfo.ERROR);
  8. errorInfo.setMessge("show error infomation");
  9. errorInfo.setUrl("www.baidu.com");
  10. errorInfo.setData(req.getRequestURI().toString());
  11. return errorInfo;
  12. }
  13. }

4、具体使用

  1. @RequestMapping(value = "/errorJson",method = RequestMethod.GET)
  2. public String errorJson() throws MyException {
  3. throw new MyException("自定义异常!");
  4. }

5、访问localhost:8080/errorJson

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/数据结构灵魂/article/detail/62650
推荐阅读
相关标签
  

闽ICP备14008679号