通过自定义异常拦截器,讲程序异常,转化为 org.springframework.http.ResponseEntity.ResponseEntity,这个类允许自定义任意的状态码和错误数据。
代码 1 2 3 4 5 6 7 8 9 public void save (BusUser busUser) { BusUser.checkAccountAndPasswordNotNull(busUser); if (busUserRepository.findByAccount(busUser.getAccount()).size() != 0 ) { throw new ApiException (ErrorType.SAVE_EXIST, "账号已经存在!" ); } busUserRepository.save(busUser); log.info("增加了一个用户:" + busUser.getAccount()); }
GlobalExceptionHandler.class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package pri.anarckk.common;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.ResponseEntity;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.mvc.method.annotation.ResponseEntityExceptionHandler;import pri.anarckk.common.entity.ErrorEntity;import pri.anarckk.common.exception.ApiException;@ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ResponseBody @ExceptionHandler public ResponseEntity<ErrorEntity> handleException (Exception e) { if (e instanceof ApiException) { ApiException apiException = (ApiException) e; ErrorType code = apiException.getCode(); apiException.error(logger); return new ResponseEntity <>(new ErrorEntity (code.code(), apiException.getMessage()), code.httpStatus()); } else { logger.error(e.getMessage(), e); return new ResponseEntity <>(new ErrorEntity (ErrorType.UN_KNOW.code(), ErrorType.UN_KNOW.message()), ErrorType.UN_KNOW.httpStatus()); } } }