The 400 or 404 pages that come with SpringMVC are all web pages, which are not suitable for the json data required by the client.
Default 404 :
Default 400 pages :
How to implement custom response to these errors?
Define a ControllerAdvice class:
Add the following two methods in it to respond 400 and 404 respectively:
/***
* 响应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;
}
My processing method is to return json, the result:
{
"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
}
You can customize the BusinessExceptionUtil.dealException method in my code.
My code base in the code cloud: