Spring boot 异常统一类返回页面 - 06

1.application

#Exception
spring.mvc.throwExceptionIfNoHandlerFound=true
#不要为我们工程中的资源文件建立映射
#spring.resources.addMappings=false

2.创建异常类,MyExceptionHandler

package com.spring.boot.exception;

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.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@ResponseBody
public class MyExceptionHandler{

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e){
        ModelAndView mav = new ModelAndView("error"); // 设置跳转路径
        mav.addObject("exception", e); // 将异常对象传递过去
        mav.addObject("url", request.getRequestURL()); // 获得请求的路径
        return mav;
    }
}

注:application必须添加,自己试验条件

猜你喜欢

转载自blog.csdn.net/qq_41920732/article/details/86032956