GlobalExceptionHandler.java 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package fr.triplea.demovote.security;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.ResponseStatus;
  9. import org.springframework.web.bind.annotation.RestControllerAdvice;
  10. import fr.triplea.demovote.dto.JsonErrorResponse;
  11. import fr.triplea.demovote.security.jwt.RefreshTokenException;
  12. @RestControllerAdvice
  13. public class GlobalExceptionHandler
  14. {
  15. //@SuppressWarnings("unused")
  16. private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  17. @Value("${production.mode}")
  18. private boolean modeProduction;
  19. @ExceptionHandler(value = RefreshTokenException.class)
  20. @ResponseStatus(HttpStatus.FORBIDDEN)
  21. public ResponseEntity<JsonErrorResponse> handleTokenRefreshException(RefreshTokenException ex)
  22. {
  23. LOG.error(ex.getMessage()); //ex.printStackTrace();
  24. JsonErrorResponse jer = new JsonErrorResponse(HttpStatus.FORBIDDEN.value(), ex.getMessage());
  25. return new ResponseEntity<>(jer, HttpStatus.FORBIDDEN);
  26. }
  27. @ExceptionHandler(Exception.class)
  28. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  29. public ResponseEntity<JsonErrorResponse> handleAllExceptions(Exception ex)
  30. {
  31. LOG.error(ex.getMessage()); //ex.printStackTrace();
  32. String message = ex.getMessage();
  33. if (modeProduction) { if (message.contains("JDBC") || message.contains("SQL")) { message = "JDBC or SQL error, please contact the administrator to look in logs"; } }
  34. JsonErrorResponse jer = new JsonErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
  35. return new ResponseEntity<>(jer, HttpStatus.INTERNAL_SERVER_ERROR);
  36. }
  37. @ExceptionHandler(NullPointerException.class)
  38. @ResponseStatus(HttpStatus.BAD_REQUEST)
  39. public ResponseEntity<JsonErrorResponse> handleNullPointerException(NullPointerException ex)
  40. {
  41. LOG.error(ex.getMessage()); //ex.printStackTrace();
  42. JsonErrorResponse jer = new JsonErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
  43. return new ResponseEntity<>(jer, HttpStatus.BAD_REQUEST);
  44. }
  45. @ExceptionHandler(ResourceNotFoundException.class)
  46. public ResponseEntity<JsonErrorResponse> handleNotFound(ResourceNotFoundException ex)
  47. {
  48. LOG.error(ex.getMessage()); //ex.printStackTrace();
  49. JsonErrorResponse jer = new JsonErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage());
  50. return new ResponseEntity<>(jer, HttpStatus.NOT_FOUND);
  51. }
  52. }