Skip to content

全局异常捕获

/src/main/java/com/example/xys1/handler/GlobalExceptionHandler.java 文件中写入以下代码

java
package com.example.xys1.handler;

import com.example.xys1.utils.res.ResUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 兜底
     */
    @ExceptionHandler(Exception.class)
    public ResUtil<?> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("发生系统异常。请求地址:{}", requestURI, e);
        return ResUtil.fail("系统异常");
    }
}