springMVC 自定义400或404页面/接口 - Go语言中文社区

springMVC 自定义400或404页面/接口


SpringMVC 自带的400404 页面都是网页,不太适用于客户端需要的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

转载于:https://my.oschina.net/huangweiindex/blog/1632499

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_34336526/article/details/92673514
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 19:39:00
  • 阅读 ( 1285 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢