欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC全局异常处理

程序员文章站 2022-04-21 23:48:23
...

 由于我使用了lombok,所以可以通过@Slf4j获取到一个log对象。JSONResult可以通过普通的map集合代替。

package com.xxx.xxxx.controller;

import com.xxx.xxxx.pojo.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 全局捕捉异常
 */
@Slf4j
@RestControllerAdvice("com.xxx.xxxx.controller")
public class GlobalExceptionHandler {

    // 设置一个错误页面
    private static final String ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest request, Exception e) {

        log.error("url: " + request.getRequestURL() + " -> exception: " + e.getMessage());

        if (isAjax(request)) {
            return JSONResult.errorException(e.getMessage());
        } else {
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e);
            mav.addObject("url", request.getRequestURL());
            mav.setViewName(ERROR_VIEW);
            return mav;
        }
    }

    /**
     * @Description: 判断是否是ajax请求
     */
    private static boolean isAjax(HttpServletRequest httpRequest) {
        return (httpRequest.getHeader("X-Requested-With") != null &&
                "XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With")));
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>捕捉全局异常</title>
</head>
<body>
    <h1 style="color: red">发生错误:</h1>
    <div>${url}</div>
    <div>${exception.message}</div>
</body>
</html>