PostManHttp请求模拟工具,软件下载链接如下
PostMan下载链接
可以参照ErrorMvcAutoConfiguration;错误处理的自动配置;
给容器中添加了以下组件:
1、DefaultErrorAttributes:
2、BasicErrorController:处理默认/error请求
3、ErrorPageCustomizer:错误页面定制
4、DefaultErrorViewResolver:
步骤:
一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error
请求: 就会被BasicErrorController处理;
响应页面: 去哪个页面是由DefaultErrorViewResolver解析得到的;
如何定制错误响应
自定义异常:
public class UserNotFoundException extends RuntimeException
{
public UserNotFoundException()
{
super(“用户不存在”);//错误显示
}
}
如何定制错误的JSON数据
@ControllerAdvice//处理全局异常的类
public class exception
{
//浏览器客户端返回的都是JSON数据
@ResponseBody
@ExceptionHandler(Exception.class)
public Map
Map
map.put(“code”,“user.notexist”);
map.put(“message”,e.getMessage());
return map;
}
}
上面的写法没有自适应效果,即浏览器访问返回一个错误页面,其他客户端访问,返回一个JSON数据
这里没有设置错误状态码,转发成功后,状态码为200,因此无法走到定制错误页面解析流程
@ControllerAdvice//处理全局异常的类
public class exception
{
@ExceptionHandler(UserNotFoundException.class)
public String handleException(Exception e){
Map
map.put(“code”,“user.notexist”);
map.put(“message”,e.getMessage());
//转发到error请求
//BasicErrorController:处理默认/error请求
return “forward:/error”;
}
}
@ControllerAdvice//处理全局异常的类
public class exception
{
@ExceptionHandler(UserNotFoundException.c
lass)
public String handleException(Exception e, HttpServletRequest request){
Map
//传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
/**
.getAttribute(“javax.servlet.error.status_code”);
*/
request.setAttribute(“javax.servlet.error.status_code”,400);
map.put(“code”,“user.notexist”);
map.put(“message”,e.getMessage());
//转发到error请求
//BasicErrorController:处理默认/error请求
return “forward:/error”;
}
}
1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;
2、页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;
自定义ErrorAttributes(错误属性)
这里springboot都是去容器中查看用户是否存在上面的错误相关的类,如果没有才会使用默认的配置类,因此我们可以通过重写上面的错误类,放入容器中,完成定制错误数据并携带出去
//给容器中加入我们自己定义的ErrorAttributes
@Component
class MyErrorAttributes extends DefaultErrorAttributes
{
//返回值的map就是和页面json能获取的数据
@Override
public Map
Map
map.put(“company”,“大忽悠集团有限公司”);
return map;
}
}
最终的效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容
HR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUzMTU3MTcz,size_16,color_FFFFFF,t_70)