当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot统一异常处理详解

Spring Boot统一异常处理详解

2019年07月22日  | 移动技术网IT编程  | 我要评论
spring boot中默认带了error的映射,但是这个错误页面显示给用户并不是很友好。 统一异常处理 通过使用@controlleradvice定义统一异常处理的类

spring boot中默认带了error的映射,但是这个错误页面显示给用户并不是很友好。

统一异常处理

通过使用@controlleradvice定义统一异常处理的类,而不是在每个controller中逐个定义。

@exceptionhandler用来定义函数针对的函数类型,最后将exception对象和请求url映射到url中。

@controlleradvice
class exceptiontranslator {
 public static final string default_error_view = "error";
 @exceptionhandler(value = exception.class)
 public modelandview defaulterrorhandler(httpservletrequest req, exception e) throws exception {
  modelandview mav = new modelandview();
  mav.addobject("exception", e);
  mav.addobject("url", req.getrequesturl());
  mav.setviewname(default_error_view);
  return mav;
 }
}

实现error.html页面展示

在templates目录下创建error.html。

例如:

<!doctype html> 
<html> 
<head lang="en"> 
 <meta charset="utf-8" />
 <title>统一异常处理</title>
</head> 
<body> 
 <h1>error handler</h1>
 <div th:text="${url}"></div>
 <div th:text="${exception.message}"></div>
</body> 
</html>

返回使用json格式

只需在@exceptionhandler之后加入@responsebody,就能让处理函数return的内容转换为json格式

创建一个json返回对象,如:

public class errordto implements serializable {
 private static final long serialversionuid = 1l;
 private final string message;
 private final string description;
 private list<fielderrordto> fielderrors;
 //getter和setter省略
}

可以为指定的exception添加异常处理

@exceptionhandler(concurrencyfailureexception.class)
 @responsestatus(httpstatus.conflict)
 @responsebody
 public errordto processconcurencyerror(concurrencyfailureexception ex) {
  return new errordto(errorconstants.err_concurrency_failure);
 }

errorconstants.err_concurrency_failure 是定义的一个异常信息。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网