GlobalExceptionHandler.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package com.zhentao.exception;
  2. import com.zhentao.vo.Result;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.web.bind.MethodArgumentNotValidException;
  5. import org.springframework.web.bind.annotation.ControllerAdvice;
  6. import org.springframework.web.bind.annotation.ExceptionHandler;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import org.springframework.web.bind.annotation.RestControllerAdvice;
  9. import org.springframework.web.multipart.MultipartException;
  10. import javax.servlet.http.HttpServletRequest;
  11. @Slf4j
  12. @RestControllerAdvice
  13. @ControllerAdvice
  14. public class GlobalExceptionHandler {
  15. // 捕获所有异常的处理器,指定捕获的异常类型为Exception
  16. @ExceptionHandler(value = Exception.class)
  17. // 将处理结果以JSON格式返回
  18. @ResponseBody
  19. public Result defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
  20. // 记录异常信息到日志,这里只记录异常信息,不记录堆栈信息
  21. log.error(e.getMessage());
  22. // 判断异常类型并进行处理
  23. if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
  24. // 如果是404异常,即没有找到处理器
  25. return Result.error(404,"不存在页面请求");
  26. }
  27. if (e instanceof AsynException) {
  28. // 如果是自定义的AsynException
  29. AsynException customException = (AsynException) e;
  30. // 返回自定义异常的错误码和错误信息
  31. return Result.error(customException.getCode(), customException.getMessage());
  32. } else if (e instanceof MultipartException) {
  33. // 如果是文件上传异常
  34. log.error("系统异常{}", e); // 记录异常堆栈信息
  35. return Result.error(1000, "上传文件异常");
  36. } else if (e instanceof MethodArgumentNotValidException) {
  37. // 如果是校验异常,例如使用@Valid注解校验参数失败
  38. MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
  39. // 获取校验失败的第一个字段的错误信息
  40. return Result.error(1002, methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage());
  41. } else {
  42. // 其他未处理的异常
  43. log.error("系统异常{}", e); // 记录异常堆栈信息
  44. return Result.error(1001, "系统参数异常");
  45. }
  46. }
  47. }