Springboot工程下处理异常,统一捕获异常以及处理404页面异常的过程,参考来自互联网博文。
统一异常处理,返回JSON
SpringBoot的项目已经对有一定的异常处理了,但是对于我们开发者而言可能就不太合适了,因此我们需要对这些异常进行统一的捕获并处理。SpringBoot中有一个ControllerAdvice的注解,使用该注解表示开启了全局异常的捕获,我们只需在自定义一个方法使用ExceptionHandler注解然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。
文章参考地址:
SpringBoot优雅的全局异常处理
https://www.cnblogs.com/xuwujing/p/10933082.html
运行结果:
发送json格式,记得postman中选项。
统一异常处理,返回页面
SpringBoot自定义错误页面与全局异常处理https://www.jianshu.com/p/a4b18d54f826
解决页面不存在的访问
SpringBoot下Controller可以返回到视图渲染也可以直接返回JSON格式,访问地址不存在时出现上面的界面。可以通过自定义的方式替换404页面。
- 自定义错误页面
首先,在我们的Spring Boot项目目录/src/main/resources/static下新建自定义错误页面404.html,具体代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>404页面</title>
</head>
<body>
<div class="text" style="text-align: center;">
我累了,让我休息一会!
</div>
</body>
</html>
- 增加一个配置类:
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
registry.addErrorPages(error404Page);
}
}
SpringBoot 404等异常时返回JSON字符串
SpringBoot 404等异常时返回JSON字符串
https://www.jianshu.com/p/a5308ba4ca6b
- 步骤一在application.properties文件中添加如下两句:
#没有绑定的url直接抛出错误
spring.mvc.throw-exception-if-no-handler-found=true
#不为静态文件建立映射
spring.resources.add-mappings=false
- 步骤二自定义一个异常处理类AllExceptionHandler
@RestControllerAdvice
public class AllExceptionHandler {
private static Logger logger = LoggerFactory.getLogger(AllExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
public Msg defaultErrorHandler(Exception e) {
logger.error("AllExceptionHandler ", e);
if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
//404 Not Found
return new Msg(404, e.getMessage());
} else {
//500
return new Msg(500, e.getMessage());
}
}
}
自定义的Msg类:
public class Msg {
/**
* 返回码
*/
private int resultCode;
/**
* 备注信息
*/
private String info;
/**
* 空构造函数
*/
public Msg() {
}
/**
* 自定义消息
*
* @param resultCode resultCode
* @param info info
*/
public Msg(int resultCode, String info) {
this.resultCode = resultCode;
this.info = info;
}
...
}
404(请求路径错误), 403(请求限制)等错误的处理
springboot默认是由BasicErrorController来处理的, 返回对应的错误页面. 这显示不是我们想要的!
新建一个controller来接管错误处理
根据文档,有两种类型HttpStatusCodeException HttpClientErrorException和HttpServerErrorException。
收到HTTP 4xx时会抛出前者。
收到HTTP 5xx时会抛出后者。
所以你可以使用ResponseEntity.BodyBuilder.status(505)来举起HttpServerErrorException你的