com.zrun.commons.web.handler.GlobalExceptionHandler Maven / Gradle / Ivy
The newest version!
package com.zrun.commons.web.handler;
import cn.hutool.core.util.ObjectUtil;
import com.zrun.commons.core.exception.DemoModeException;
import com.zrun.commons.core.exception.ServiceException;
import com.zrun.commons.core.model.R;
import com.zrun.commons.core.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
/**
* 全局异常处理器
*
* @author zrun
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 业务异常
*
* @param e
* @param request
* @return
*/
@ExceptionHandler(ServiceException.class)
public R handleServiceException(ServiceException e, HttpServletRequest request) {
Integer code = e.getCode();
if (code == null || R.ERROR == code) {
log.error(e.getMessage(), e);
} else {
log.warn(e.getMessage(), e);
}
return ObjectUtil.isNotNull(code) ? R.error(code.intValue(), e.getMessage()) : R.error(e.getMessage());
}
/**
* 自定义验证异常
*
* @param e
* @return
*/
@ExceptionHandler(BindException.class)
public R handleBindException(BindException e, HttpServletRequest request) {
logError(e, request, "绑定异常");
return R.error(e.getAllErrors().get(0).getDefaultMessage());
}
/**
* 自定义验证异常
*
* @param e
* @return
*/
@ExceptionHandler({MethodArgumentNotValidException.class})
public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
logError(e, request, "参数校验异常");
FieldError fieldError = e.getBindingResult().getFieldError();
return R.error(fieldError.getField() + fieldError.getDefaultMessage());
}
/**
* @param e
* @return
*/
@ExceptionHandler(ServletRequestBindingException.class)
public R handleServletRequestBindingException(ServletRequestBindingException e, HttpServletRequest request) {
logError(e, request, "参数异常");
return R.error(e.getMessage());
}
/**
* 系统异常
*
* @param e
* @param request
* @return
*/
@ExceptionHandler(Exception.class)
public R handleException(Exception e, HttpServletRequest request) {
logError(e, request, "未知异常");
return R.error(e.getMessage());
}
/**
* 演示模式异常
*
* @param e
* @return
*/
@ExceptionHandler(DemoModeException.class)
public R handleDemoModeException(DemoModeException e) {
return R.error("演示模式,不允许操作");
}
private void logError(Exception e, HttpServletRequest request, String msg){
String requestURI = request.getRequestURI();
log.error("{},地址:{},入参:{}", msg, requestURI, ServletUtils.getRequestParam(request), e);
}
}