使用@ExceptionHandler注解拦截异常,DefaultErrorAttributes自定义发送的错误信息

import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

@Component
public class MyErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map map = super.getErrorAttributes(webRequest, includeStackTrace);
        map.put("fuck","you");
        //从request域获取exist内容,会发送到错误页面
        Map exist= (Map) webRequest.getAttribute("exist",0);
        map.put("exist",exist);
        return map;
    }
}
import com.yhy.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(UserNotExistException.class)
    public String handlerException(Exception e, HttpServletRequest request) {
        HashMap map = new HashMap<>();
        //自定义错误状态码,会转发到4xx页面,如果是502,在error文件夹下面建立一个5xx.html就行
        request.setAttribute("javax.servlet.error.status_code",400);
        map.put("code","user.notexist");
        map.put("message","用户并没有存在");
        //错误信息设置到request
        request.setAttribute("exist",map);
        return "forward:/error";
    }
}

自定义4xx页面,输出自定义信息,thymeleaf直接放error下面,其他不懂使用@ExceptionHandler注解拦截异常,DefaultErrorAttributes自定义发送的错误信息_第1张图片

你可能感兴趣的:(spring,boot)