摘要: SpringMVC 自带的400或404 页面都是网页,不太适用于客户端需要的json数据
SpringMVC 自带的400或404 页面都是网页,不太适用于客户端需要的json数据,
默认的404:
默认的400页面:
如何实现对这些错误的响应自定义呢?
定义一个 ControllerAdvice 类:
在其中添加如下两个方法,分别响应400和404:
/***
* 响应400错误
* @param ex
* @param session
* @param request
* @param response
* @return
*/
@ExceptionHandler(org.springframework.beans.TypeMismatchException.class)
public String handle400Exception2(org.springframework.beans.TypeMismatchException ex, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
String respCode = "400";
logger.error(respCode, ex);
LogicBusinessException logicBusinessException = new LogicBusinessException();
logicBusinessException.setErrorCode(respCode);
logicBusinessException.setErrorMessage(ex.getValue() + " " + ex.getMessage());
BusinessExceptionUtil.dealException(logicBusinessException, response);
return null;
}
/***
* 响应404 错误
* @param ex
* @param session
* @param request
* @param response
* @return
*/
@ExceptionHandler(org.springframework.web.servlet.NoHandlerFoundException.class)
//org.springframework.web.servlet.NoHandlerFoundException: No handler found for GET /agent2/follow/query/json, headers={host=[127.0.0.1:8080], connection=[keep-alive], upgrade-insecure-requests=[1]}
public String handleNotFound404Exception2(org.springframework.web.servlet.NoHandlerFoundException ex, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
String respCode = "404";
logger.error(respCode, ex);
LogicBusinessException logicBusinessException = new LogicBusinessException();
logicBusinessException.setErrorCode(respCode);
logicBusinessException.setErrorMessage(ex.getRequestURL() + " " + SystemHWUtil.splitAndFilterString(ex.getMessage(), 60));
BusinessExceptionUtil.dealException(logicBusinessException, response);
return null;
}
我的处理方法是返回json,结果:
{ "result": false, "param": null, "errorCode": "404", "value": null, "error": { "code": "404", "hint": null, "msg": "/cooperate2/myReceived/listfilter/json No handler found for GET /cooperate2/myReceived/listfilter/j......" }, "extraInfo": null }
各位可以自定义我代码中的BusinessExceptionUtil.dealException 方法.
我在码云的代码库:
https://gitee.com/kunlunsoft/inetAdress_socket
https://gitee.com/kunlunsoft/stub_test