1. 首先定义全局异常处理类
import org.springframework.validation.BindException;
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.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.net.ConnectException;
@ControllerAdvice
public class GlobalExceptionHandler {
//@ExceptionHandler(BindException.class)
//多个异常用逗号分隔
@ExceptionHandler({
NoHandlerFoundException.class,
HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class,
MissingPathVariableException.class,
})
@ResponseBody
public ModelAndView handleBindException(BindException e, HttpServletRequest request) {
request.setAttribute("errMsg", e.getFieldError().getDefaultMessage()); //需求时间初始化为当前日期
return new ModelAndView("Error");
}
@ExceptionHandler(ConnectException.class) //连接超时
@ResponseBody
public ModelAndView handleException(Exception e, HttpServletRequest request) {
request.setAttribute("errMsg", "系统繁忙,请稍后再试"); //需求时间初始化为当前日期
return new ModelAndView("Error");
}
@ExceptionHandler(IllegalStateException.class) //子模块还未启动成功
@ResponseBody
public ModelAndView handleIllegalStateException(Exception e, HttpServletRequest request) {
request.setAttribute("errMsg", "子模块还未启动成功,请稍后再试"); //需求时间初始化为当前日期
return new ModelAndView("Error");
}
}
2. 当全局有接口返回已经定义的全局捕捉的异常,就会调用上面的接口统一返回信息
3. 统一返回错误页面 Error.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<TITLE>错误页面</TITLE>
</HEAD>
<BODY>
<div id="errorBox">
<ul>
<li><img src="/css/img/error.png"></li>
<li class="msg"><p id="errMsg" th:text="'错误提示:'+ ${errMsg}" /></li>
</ul>
</div>
</BODY>
</HTML>
当前端访问/getJobList接口时如果微服务的其他模块还未启动IllegalStateException异常就会被拦截从而重定向到Error页面,并输出错误信息:文章来源:https://www.toymoban.com/news/detail-654500.html
文章来源地址https://www.toymoban.com/news/detail-654500.html
到了这里,关于java全局捕捉异常并返回统一返回值的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!