CommonExceptionAdvice.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.zksy.common.advice;
  2. import com.zksy.common.core.domain.Result;
  3. import com.zksy.common.exception.BadRequestException;
  4. import com.zksy.common.exception.CommonException;
  5. import com.zksy.common.exception.DbException;
  6. import com.zksy.common.utils.WebUtils;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.validation.ObjectError;
  10. import org.springframework.web.bind.MethodArgumentNotValidException;
  11. import org.springframework.web.bind.annotation.ExceptionHandler;
  12. import org.springframework.web.bind.annotation.RestControllerAdvice;
  13. import org.springframework.web.util.NestedServletException;
  14. import java.net.BindException;
  15. import java.util.stream.Collectors;
  16. @RestControllerAdvice
  17. @Slf4j
  18. public class CommonExceptionAdvice {
  19. @ExceptionHandler(DbException.class)
  20. public Object handleDbException(DbException e) {
  21. log.error("mysql数据库操作异常 -> ", e);
  22. return processResponse(e);
  23. }
  24. @ExceptionHandler(CommonException.class)
  25. public Object handleBadRequestException(CommonException e) {
  26. log.error("自定义异常 -> {} , 异常原因:{} ",e.getClass().getName(), e.getMessage());
  27. log.debug("", e);
  28. return processResponse(e);
  29. }
  30. @ExceptionHandler(MethodArgumentNotValidException.class)
  31. public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
  32. String msg = e.getBindingResult().getAllErrors()
  33. .stream().map(ObjectError::getDefaultMessage)
  34. .collect(Collectors.joining("|"));
  35. log.error("请求参数校验异常 -> {}", msg);
  36. log.debug("", e);
  37. return processResponse(new BadRequestException(msg));
  38. }
  39. @ExceptionHandler(BindException.class)
  40. public Object handleBindException(BindException e) {
  41. log.error("请求参数绑定异常 ->BindException, {}", e.getMessage());
  42. log.debug("", e);
  43. return processResponse(new BadRequestException("请求参数格式错误"));
  44. }
  45. @ExceptionHandler(NestedServletException.class)
  46. public Object handleNestedServletException(NestedServletException e) {
  47. log.error("参数异常 -> NestedServletException,{}", e.getMessage());
  48. log.debug("", e);
  49. return processResponse(new BadRequestException("请求参数处理异常"));
  50. }
  51. @ExceptionHandler(Exception.class)
  52. public Object handleRuntimeException(Exception e) {
  53. log.error("其他异常 uri : {} -> ", WebUtils.getRequest().getRequestURI(), e);
  54. return processResponse(new CommonException("服务器内部异常", 500));
  55. }
  56. private ResponseEntity<Result<Void>> processResponse(CommonException e){
  57. return ResponseEntity.status(e.getCode()).body(Result.error(e));
  58. }
  59. }