柯桥增值式服务
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
2.5KB

  1. package com.ningdatech.kqapi.common.handler;
  2. import com.ningdatech.kqapi.common.model.ApiResponse;
  3. import com.ningdatech.kqapi.common.model.Status;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.context.support.DefaultMessageSourceResolvable;
  6. import org.springframework.http.HttpStatus;
  7. import org.springframework.validation.BindException;
  8. import org.springframework.web.bind.MethodArgumentNotValidException;
  9. import org.springframework.web.bind.annotation.ControllerAdvice;
  10. import org.springframework.web.bind.annotation.ExceptionHandler;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. import org.springframework.web.bind.annotation.ResponseStatus;
  13. import org.springframework.web.servlet.NoHandlerFoundException;
  14. import javax.validation.ConstraintViolation;
  15. import javax.validation.ConstraintViolationException;
  16. import java.util.stream.Collectors;
  17. /**
  18. * @description: 统一错误处理
  19. * @author: liuxinxin
  20. * @date: 2023/01/03 11:39
  21. */
  22. @Slf4j
  23. @ControllerAdvice
  24. @ResponseStatus(HttpStatus.BAD_REQUEST)
  25. public class GlobalExceptionHandler {
  26. @ResponseBody
  27. @ExceptionHandler(value = NoHandlerFoundException.class)
  28. public ApiResponse<Void> noHandlerFoundException(NoHandlerFoundException e) {
  29. log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", e.getRequestURL(), e.getHttpMethod());
  30. return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND);
  31. }
  32. @ResponseBody
  33. @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
  34. public ApiResponse<Void> bindException(BindException e) {
  35. String msg = e.getAllErrors().stream()
  36. .map(DefaultMessageSourceResolvable::getDefaultMessage)
  37. .collect(Collectors.joining(","));
  38. return ApiResponse.of(Status.BAD_REQUEST.getCode(), msg, null);
  39. }
  40. @ResponseBody
  41. @ExceptionHandler(value = ConstraintViolationException.class)
  42. public ApiResponse<Void> constraintViolationException(ConstraintViolationException e) {
  43. String msg = e.getConstraintViolations().stream()
  44. .map(ConstraintViolation::getMessage)
  45. .collect(Collectors.joining(","));
  46. return ApiResponse.of(Status.BAD_REQUEST.getCode(), msg, null);
  47. }
  48. @ResponseBody
  49. @ExceptionHandler(value = Exception.class)
  50. public ApiResponse<Void> handlerException(Exception e) {
  51. log.error("【全局异常拦截】: 异常信息 {}: {} ", e.getClass().getSimpleName(), e);
  52. return ApiResponse.of(Status.BAD_REQUEST.getCode(), e.getMessage(), null);
  53. }
  54. }