28.Spring-Boot 1.5版错误处理2.0版错误处理有改动

       Spring Boot在默认情况下提供了一个/error,以合理的方式处理所有错误。它在servlet容器中注册为“全局”错误页面。对于机器客户机(类似ajax),它将生成一个JSON响应,其中包含错误的详细信息、HTTP状态和异常消息。对于浏览器客户端,有一个“whitelabel”错误视图,它以HTML格式呈现相同的数据(为了定制它只是添加了一个解析为“error”的视图)。要完全替换默认行为,您可以实现ErrorController并注册该类型的bean定义,或者简单地添加一个类型ErrorAttributes的bean来使用现有的机制,但要替换其中的内容

//ajax 返回json错误

{"timestamp":1527659553067,"status":500,"error":"InternalServer Error","exception":"com.niugang.exception.CheckException","message":"用户名不能为空","path":"/myweb/save"}

//浏览器请求 返回一个whitelabel视图

  提示:

    可以将BasicErrorController用作自定义ErrorController的基类。如果您想为一个新的内容类型添加一个处理程序,这一点特别有用(默认情况下是处理text/html,并为其他所有内容提供一个回退)。要做到这一点,只需扩展BasicErrorController,并添加一个带有生成属性的@RequestMapping的公共方法,并创建一个新类型的bean。【这点笔者尝试一直有问题】

推荐:通过@ControllerAdvice 返回定制的json错误文档,替换默认的。


1.自定义错误类型类
package com.niugang.exception;


public class CustomErrorType {
/**
* 状态码
*/
    private  int status;
    /**
     * 错误信息
     */
    private  String message;
    
public CustomErrorType(int status, String message) {
super();
this.status = status;
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
    
}
2.统一提示类
package com.niugang.exception;

import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * 返回订制的json文档错误
 * 对于javaweb中
 * @author niugang
 *
 */
@ControllerAdvice
public class ControllerAdviceException extends ResponseEntityExceptionHandler {

@ExceptionHandler({CheckException.class,RuntimeException.class})
@ResponseBody
ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
HttpStatus status = getStatus(request);
//返回格式
               //{"status":500,"message":"用户名不能为空"} 最终返回的格式
return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);

}

     private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}
}

推荐:自定义错误页面

如果您想为给定的状态代码显示一个自定义的HTML错误页面,您可以向/error文件夹中添加一个文件。

src/
+- main/
+- java/
| + <source code>
+- resources/
    +- public/    默认存放静态文件,文件夹
       +- error/   必须有的文件下,springboot默认的error.html文件就是在error文件夹下的

          | +- 404.html

          | +- 500.html

+- <other public assets>

对于以上所有基于浏览器的请求,当出现404时,就是跳转到404.html页面,出现500错误时,就会跳转到500.html页面。

 微信公众号

 

 

原文地址:https://www.cnblogs.com/niugang0920/p/12193080.html