Spring Boot 统一异常处理的案例

ゝ一纸荒年。 2024-02-18 16:49 130阅读 0赞

统一异常处理:统一处理程序中抛出的所有或特定异常.

1.返回页面的数据类型为:Json格式

  1. package com.example.demo.error;
  2. /**
  3. * Create by szw on 2017/11/29 16:31
  4. */
  5. public class ErrorInfo<T> {
  6. public static final Integer OK = 0;
  7. public static final Integer ERROR = 100;
  8. private Integer code;
  9. private String message;
  10. private T data;
  11. public static Integer getOK() {
  12. return OK;
  13. }
  14. public static Integer getERROR() {
  15. return ERROR;
  16. }
  17. public Integer getCode() {
  18. return code;
  19. }
  20. public void setCode(Integer code) {
  21. this.code = code;
  22. }
  23. public String getMessage() {
  24. return message;
  25. }
  26. public void setMessage(String message) {
  27. this.message = message;
  28. }
  29. public T getData() {
  30. return data;
  31. }
  32. public void setData(T data) {
  33. this.data = data;
  34. }
  35. }

2.自定义异常类

  1. package com.example.demo.exception;
  2. import sun.plugin2.message.Message;
  3. /**
  4. * Create by szw on 2017/11/29 16:32
  5. */
  6. public class MyException extends Exception {
  7. public MyException(String message) {
  8. super(message);
  9. }
  10. }

3.统一异常处理

  1. package com.example.demo.exception;
  2. /**
  3. * Create by szw on 2017/11/29 15:59
  4. */
  5. import com.example.demo.error.ErrorInfo;
  6. import org.springframework.web.bind.annotation.ControllerAdvice;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import org.springframework.web.servlet.ModelAndView;
  10. import javax.servlet.http.HttpServletRequest;
  11. /**
  12. * 统一异常处理
  13. */
  14. @ControllerAdvice
  15. class GlobalExceptionHandler {
  16. public static final String DEFAULT_ERROR_VIEW = "error";
  17. @ExceptionHandler(value = MyException.class)
  18. @ResponseBody
  19. public ErrorInfo defaultErrorHandler(HttpServletRequest req, MyException e) throws Exception {
  20. ErrorInfo<String> stringErrorInfo = new ErrorInfo<>();
  21. stringErrorInfo.setMessage(e.getMessage());
  22. stringErrorInfo.setCode(ErrorInfo.ERROR);
  23. stringErrorInfo.setData("some date");
  24. return stringErrorInfo;
  25. }
  26. }

发表评论

表情:
评论列表 (有 0 条评论,130人围观)

还没有评论,来说两句吧...

相关阅读