springMVC 自定义400或404页面/响应

236 篇文章 0 订阅
25 篇文章 0 订阅
摘要: SpringMVC 自带的400或404 页面都是网页,不太适用于客户端需要的json数据

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

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值