1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package com.zhentao.exception;
- import com.zhentao.vo.Result;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.web.bind.MethodArgumentNotValidException;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
- import org.springframework.web.multipart.MultipartException;
- import javax.servlet.http.HttpServletRequest;
- @Slf4j
- @RestControllerAdvice
- @ControllerAdvice
- public class GlobalExceptionHandler {
- // 捕获所有异常的处理器,指定捕获的异常类型为Exception
- @ExceptionHandler(value = Exception.class)
- // 将处理结果以JSON格式返回
- @ResponseBody
- public Result defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
- // 记录异常信息到日志,这里只记录异常信息,不记录堆栈信息
- log.error(e.getMessage());
- // 判断异常类型并进行处理
- if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
- // 如果是404异常,即没有找到处理器
- return Result.error(404,"不存在页面请求");
- }
- if (e instanceof AsynException) {
- // 如果是自定义的AsynException
- AsynException customException = (AsynException) e;
- // 返回自定义异常的错误码和错误信息
- return Result.error(customException.getCode(), customException.getMessage());
- } else if (e instanceof MultipartException) {
- // 如果是文件上传异常
- log.error("系统异常{}", e); // 记录异常堆栈信息
- return Result.error(1000, "上传文件异常");
- } else if (e instanceof MethodArgumentNotValidException) {
- // 如果是校验异常,例如使用@Valid注解校验参数失败
- MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
- // 获取校验失败的第一个字段的错误信息
- return Result.error(1002, methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage());
- } else {
- // 其他未处理的异常
- log.error("系统异常{}", e); // 记录异常堆栈信息
- return Result.error(1001, "系统参数异常");
- }
- }
- }
|