@ExceptionHandler 可指定Exception处理。
通过@ResponseBody 可将异常信息以json的方式返回出去
package com.antong.api.handler;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.antong.common.constant.Constants;
import com.antong.common.exception.AuthException;
import com.antong.common.util.Ret;
/**
* Copyright: Copyright (c) 2018 zq_tuo
*
* @ClassName: GlobalExceptionHandler.java
* @Description: 统一异常处理
* @version: v1.0.0
* @author: tuozq
* @date: 2018年6月26日 下午1:33:25
* Modification History:
* Date Author Version Description
*---------------------------------------------------------*
* 2018年6月26日 tuozq v1.0.0 修改原因
*/
@ControllerAdvice
public class GlobalExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "error";
/*
跳转至自定义异常界面
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", req.getRequestURL());
mav.setViewName(DEFAULT_ERROR_VIEW);
return mav;
}*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Ret defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
return Ret.fail(Constants.MESSAGE, e.getMessage()).set("uri", req.getRequestURI());
}
/**
* 针对特定异常 特殊处理
* @param req request请求
* @param e 异常对象
* @return
* @throws Exception
*/
@ExceptionHandler(value = AuthException.class)
@ResponseBody
public Ret AuthExceptionHandler(HttpServletRequest req, AuthException e) throws Exception {
return Ret.fail(Constants.MESSAGE, e.getMessage()).set(Constants.CODE, e.getCode());
}
}