package com.imed.costaccount.common.exception; import com.imed.costaccount.common.util.Result; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authz.UnauthorizedException; import org.springframework.dao.DataAccessException; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.io.UnsupportedEncodingException; import java.util.List; @Slf4j @RestControllerAdvice public class CostExceptionHandler { @ExceptionHandler(value = CostException.class) public Result handlerEmosException(CostException e) { e.printStackTrace(); log.info("GlobalExceptionHandler..."); log.info("错误代码:" + e.getMessage()); return Result.errorMsg(500, e.getMessage()); } // @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ExceptionHandler(value = MethodArgumentNotValidException.class) public Result handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) { e.printStackTrace(); log.info("GlobalExceptionHandler..."); log.info("错误代码:" + e.getMessage()); return Result.errorMsg(500, this.formatAllErrorMessages(e.getBindingResult().getAllErrors())); } // @ResponseStatus(value = HttpStatus.UNAUTHORIZED) @ExceptionHandler(value = UnauthorizedException.class) public Result handlerUnauthorizedException(UnauthorizedException e) { e.printStackTrace(); log.info("GlobalExceptionHandler..."); log.info("错误代码:" + e.getMessage()); return Result.errorMsg(403,"您的权限不足,请联系管理员添加"); } // @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ExceptionHandler(value = Exception.class) public Result handlerException(Exception e) { e.printStackTrace(); log.info("===============================GlobalExceptionHandler异常信息==============================="); log.info("错误代码:" + e.getLocalizedMessage()); return Result.errorMsg("预期之外错误,请联系管理员~"); } private String formatAllErrorMessages(List errors) { StringBuffer errorMsg = new StringBuffer(); errors.forEach(error -> { String defaultMessage = error.getDefaultMessage(); try { defaultMessage = new String(defaultMessage.getBytes("UTF-8"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } errorMsg.append(defaultMessage).append(';'); }); return errorMsg.toString(); } @ExceptionHandler(DataAccessException.class) @ResponseBody public Result handleDataAccessException(DataAccessException e) { log.error("数据库错误:{}", e.getMessage(), e); return Result.errorMsg("数据库错误"); } }