针对不同业务异常返回不同的json数据
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import com.ghgcn.support.web.BaseController;
import org.jflame.toolkit.common.bean.CallResult;
import org.jflame.toolkit.common.bean.CallResult.ResultEnum;
import org.jflame.toolkit.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
- 全局异常处理器(只处理json输出)
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
private CallResult<?> error = new CallResult<>(ResultEnum.SERVER_ERROR);
/**
* 处理参数验证异常
*
* @param request
* @param e
* @return
*/
@ExceptionHandler({ BindException.class,MethodArgumentNotValidException.class,ConstraintViolationException.class,
MissingServletRequestParameterException.class })
@ResponseBody
public CallResult<?> handValidateException(HttpServletRequest request, Exception e) {
CallResult<?> result = new CallResult<>(ResultEnum.PARAM_ERROR);
log.warn(e.getMessage());
if (e instanceof MethodArgumentNotValidException) {
BaseController.convertError(((MethodArgumentNotValidException) e).getBindingResult(), result);
} else if (e instanceof BindException) {
BaseController.convertError(((BindException) e).getBindingResult(), result);
} else if (e instanceof ConstraintViolationException) {
ConstraintViolationException cve = (ConstraintViolationException) e.getCause();
String errMsg = "";
for (ConstraintViolation<?> cv : cve.getConstraintViolations()) {
errMsg = errMsg + cv.getMessage() + ";";
}
result.setMessage(errMsg);
}
return result;
}
@ExceptionHandler({ BusinessException.class })
@ResponseBody
public CallResult<?> handBusinessException(HttpServletRequest request, BusinessException e) {
log.error("", e);
if (e.getStatus() != 0) {
return new CallResult<>(e.getStatus(), e.getMessage());
}
return error;
}
@ExceptionHandler({ Exception.class })
@ResponseBody
public CallResult<?> handException(HttpServletRequest request, Exception e) {
log.error("", e);
if (e.getCause() instanceof ConstraintViolationException) {
ConstraintViolationException cve = (ConstraintViolationException) e.getCause();
String errMsg = "";
for (ConstraintViolation<?> cv : cve.getConstraintViolations()) {
errMsg = errMsg + cv.getMessage() + ";";
}
return CallResult.paramError(errMsg);
}
return error;
}
}