修改用户登录,模拟异常
@PostMapping("/user/login")
public String login(String username, String password, HttpServletRequest httpServletRequest) throws UserNotExistException {
System.out.println("user:"+username);
System.out.println("pwd:"+password);
if("admin".equals(username)){
throw new UserNotExistException();
}
}
UserNotExistException
public class UserNotExistException extends Exception{
public UserNotExistException() {
super("用户不存在");
}
}
登录页面显示
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Jul 07 10:38:13 CST 2019
There was an unexpected error (type=Internal Server Error, status=500).
用户不存在
1)、自定义异常处理&返回定制json数据;
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map<String,Object> handleException(Exception e){
Map<String,Object> map = new HashMap<>();
map.put("code","user.notexist");
map.put("message",e.getMessage());
return map;
}
}
//没有自适应效果...
//页面和Postman工具请求都显示JSON格式:
{
"code": "user.notexist",
"message": "用户不存在"
}
2)、转发到/error进行自适应响应效果处理
@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
//传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
/**
* Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message",e.getMessage());
//转发到/error
return "forward:/error";
}
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;
2、页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;
容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;
自定义ErrorAttributes
//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
map.put("company","atguigu");
return map;
}
}
在Springboot 2.0中 ,继承 DefaultErrorAttributes,一直出现以下错误(无法找到类名):
org.springframework.web.reactive.function.server.ServerRequest
后来仔细发现,DefaultErrorAttributes 类在Springboot有2个同样的类名:
1、import org.springframework.boot.web.reactive.error.DefaultErrorAttributes
2、import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; (这是我们要用的)
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> maps = super.getErrorAttributes(webRequest, includeStackTrace);
maps.put("company","atguigu");
return maps;
}
最终的效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容,