Spring mvc 返回json时异常统一处理

加入以下代码就可以了,注意此类一定要在spring扫描的包下

import com.crm.model.common.ResponseEntity;
import com.crm.model.common.contstants.RequestStatusContants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ApplicationControllerExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(ApplicationControllerExceptionHandler.class);
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity handlerError(HttpServletRequest req, Exception e) {
        ResponseEntity entity = new ResponseEntity();
        entity.setStatus(RequestStatusContants.SERVER_ERROR_ERROR);
        entity.setMessage("系统繁忙,请稍后重试");
        logger.error("调用" + req.getRequestURI() + "错误", e);
        return entity;
    }
}

如果以上方法不能进行拦截,可以在BaseController加一个方法

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        if (e instanceof BaseException) {
            BaseException baseException = (BaseException) e;
            modelAndView = buildModelAndView("201", baseException.getMessageText());
        } else if (e instanceof OpertionException) {
            modelAndView = buildModelAndView("202", e.getMessage());
        } else {
            modelAndView = buildModelAndView("500", "系统繁忙,请稍后重试");
        }
        return modelAndView;
    }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值