| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- package easydo.technology.config.exception;
- import easydo.technology.exception.BizException;
- import lombok.extern.log4j.Log4j2;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.ResponseEntity;
- import org.springframework.validation.BindException;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * 处理Controller抛出的异常*
- * @author tianyf
- */
- @RestControllerAdvice
- @Log4j2
- public class BizExceptionHandler {
- /**
- * 处理业务异常 (BizException)
- * 返回 400 错误
- */
- @ExceptionHandler(BizException.class)
- public ResponseEntity<Object> handleBizException(BizException e) {
- log.error("[ 业务异常捕获 ] " + e.getMessage());
- Map<String, Object> vo = new HashMap<>();
- vo.put("success", false);
- vo.put("message", e.getMessage());
- vo.put("error", "");
- return new ResponseEntity<>(vo, HttpStatus.BAD_REQUEST);
- }
- /**
- * 处理所有不可知的系统异常 (Exception)
- * 返回 500 错误
- */
- @ExceptionHandler(Exception.class)
- public ResponseEntity<Object> handleException(Exception e) {
- log.error("[ 系统异常捕获 ] ", e);
- Map<String, Object> vo = new HashMap<>();
- vo.put("success", false);
- vo.put("message", "系统错误");
- vo.put("error", e.getMessage() != null ? e.getMessage() : e.getClass().getName());
- return new ResponseEntity<>(vo, HttpStatus.INTERNAL_SERVER_ERROR);
- }
- /**
- * 为 @NotNull / @NotEmpty / @NotBlank 提供异常后的消息抛出*
- * @param bindException
- * @return
- */
- @ExceptionHandler({BindException.class})
- public ResponseEntity<Object> throwCustomException(BindException bindException){
- log.error("[ @Vaild异常捕获 ] " + bindException.getMessage());
- Map<String, Object> vo = new HashMap<>();
- vo.put("success", false);
- vo.put("message", bindException.getBindingResult().getFieldError().getDefaultMessage());
- vo.put("error", "参数校验失败");
- return new ResponseEntity<>(vo, HttpStatus.BAD_REQUEST);
- }
- }
|