ExceptionHandler.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package com.api.base.config;
  2. import com.api.core.ServiceException;
  3. import com.api.core.response.Result;
  4. import com.api.core.response.ResultEnum;
  5. import com.api.core.response.ResultGenerator;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.dao.DuplicateKeyException;
  9. import org.springframework.security.web.firewall.RequestRejectedException;
  10. import org.springframework.web.HttpRequestMethodNotSupportedException;
  11. import org.springframework.web.bind.MissingServletRequestParameterException;
  12. import org.springframework.web.bind.annotation.ControllerAdvice;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14. import org.springframework.web.multipart.MaxUploadSizeExceededException;
  15. import javax.servlet.http.HttpServletRequest;
  16. import java.net.ConnectException;
  17. @ControllerAdvice
  18. public class ExceptionHandler {
  19. private Logger logger = LoggerFactory.getLogger(this.getClass());
  20. @org.springframework.web.bind.annotation.ExceptionHandler()
  21. public @ResponseBody
  22. Result defaultErrorHandler(HttpServletRequest req, Exception e) {
  23. logger.error(req.getRequestURI(), e);
  24. if (e instanceof MaxUploadSizeExceededException) return ResultGenerator.genResult(ResultEnum.UPLOADED_MAX);
  25. if (e instanceof IllegalArgumentException) return ResultGenerator.genResult(ResultEnum.DATE_ENTRY_ERROR);
  26. if (e instanceof MissingServletRequestParameterException)
  27. return ResultGenerator.genResult(ResultEnum.PARAMS_LACK);
  28. if (e instanceof ConnectException) return ResultGenerator.genResult(ResultEnum.CONNECT_EXCEPTION);
  29. if (e instanceof HttpRequestMethodNotSupportedException)
  30. return ResultGenerator.genExceptionResult(e);
  31. if (e instanceof DuplicateKeyException)
  32. return ResultGenerator.genResult(ResultEnum.DUPLICATE_KEY);
  33. if (e instanceof RequestRejectedException) return ResultGenerator.genResult(ResultEnum.INTERNAL_SERVER_ERROR);
  34. if (e instanceof ServiceException) return ResultGenerator.genExceptionResult(e);
  35. return ResultGenerator.genExceptionResult();
  36. }
  37. }