package cn.hsa.pss.pw.pcs.manage.exception;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hsa.hsaf.core.framework.web.exception.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
/**
* @Description: 全局异常处理
* @Author: Guo.Yang
* @Date: 2023/08/09/10:19
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 基础异常
*/
@ExceptionHandler(AppException.class)
public WrapperResponse<String> baseException(AppException e) {
return WrapperResponse.error(e.getCode(),e.getMessage(), null);
}
/**
* 业务异常
*/
@ExceptionHandler(RuntimeException.class)
public WrapperResponse<String> runtimeException(RuntimeException e) {
log.error("接口出现异常",e);
return WrapperResponse.error(-1, e.getMessage(), null);
}
@ExceptionHandler(NoHandlerFoundException.class)
public WrapperResponse handlerNoFoundException(Exception e) {
log.error(e.getMessage(), e);
return WrapperResponse.error(HttpStatus.NOT_FOUND.value(), "路径不存在,请检查路径是否正确", null);
}
@ExceptionHandler(AccessDeniedException.class)
public WrapperResponse handleAuthorizationException(AccessDeniedException e) {
log.error(e.getMessage());
return WrapperResponse.error(HttpStatus.FORBIDDEN.value(), "没有权限,请联系管理员授权", null);
}
@ExceptionHandler(AccountExpiredException.class)
public WrapperResponse handleAccountExpiredException(AccountExpiredException e) {
log.error(e.getMessage(), e);
return WrapperResponse.fail(e.getMessage(), null);
}
@ExceptionHandler(Exception.class)
public WrapperResponse handleException(Exception e) {
log.error(e.getMessage(), e);
return WrapperResponse.fail(e.getMessage(), null);
}
/**
* 自定义验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object validExceptionHandler(MethodArgumentNotValidException e) {
log.error(e.getMessage(), e);
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return WrapperResponse.fail(message, null);
}
}