springboot异常

x33g5p2x  于2021-09-22 转载在 Spring  
字(2.1k)|赞(0)|评价(0)|浏览(351)

1.springboot异常页面定义

1.1 资源存放的位置templates/error/或者static/error/

1.2 静态资源

1.2.1 404/400开头状态码异常界面

1.2.2 500/500开头状态码异常界面

1.3 动态资源

1.3.1 404/400开头状态码异常界面

1.3.2 500/500开头状态码异常界面

1.4 优先顺序,拿404异常来说,查找顺序如下

1.templates/error/404.html
2.static/error/404.html
3.templates/error/4xx.html
4.static/error/4xx.html

2.springboot自定义异常处理

2.1 自定义异常数据

package com.yl.exception.config;

import org.springframework.boot.web.error.ErrorAttributeOptions;
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 MyErrorAttribute extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> map = super.getErrorAttributes(webRequest, options);
        if ((Integer)map.get("status") == 404) {
            map.put("message","页面不存在");
        }
        return map;
    }
}

2.2 自定义异常数据和自定义异常视图

package com.yl.exception.config;

import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

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

/** * 这里面既可以自定义异常数据,也可以自定义异常的视图 */
@Component
public class MyErrorViewResolver extends DefaultErrorViewResolver {
    public MyErrorViewResolver(ApplicationContext applicationContext, WebProperties.Resources resources) {
        super(applicationContext, resources);
    }

    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        Map<String,Object> map = new HashMap<>();
        map.putAll(model);
        if ((Integer) model.get("status") == 500) {
            map.put("message","服务器内部异常");
        }
        //处理异常的视图位置
        ModelAndView view = new ModelAndView("yl/777",map);
        return view;
    }
}

2.3 异常视图

相关文章