Created
March 28, 2023 12:18
-
-
Save vitorgonzaga/5aefe4fd6fdca186eb320ff90be8c427 to your computer and use it in GitHub Desktop.
TratadorDeErros
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RestControllerAdvice | |
public class TratadorDeErros { | |
@ExceptionHandler(EntityNotFoundException.class) | |
public ResponseEntity tratarErro404() { | |
return ResponseEntity.notFound().build(); | |
} | |
@ExceptionHandler(MethodArgumentNotValidException.class) | |
public ResponseEntity tratarErro400(MethodArgumentNotValidException ex) { | |
var erros = ex.getFieldErrors(); | |
return ResponseEntity.badRequest().body(erros.stream().map(DadosErroValidacao::new).toList()); | |
} | |
@ExceptionHandler(HttpMessageNotReadableException.class) | |
public ResponseEntity tratarErro400(HttpMessageNotReadableException ex) { | |
return ResponseEntity.badRequest().body(ex.getMessage()); | |
} | |
@ExceptionHandler(BadCredentialsException.class) | |
public ResponseEntity tratarErroBadCredentials() { | |
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Credenciais inválidas"); | |
} | |
@ExceptionHandler(AuthenticationException.class) | |
public ResponseEntity tratarErroAuthentication() { | |
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Falha na autenticação"); | |
} | |
@ExceptionHandler(AccessDeniedException.class) | |
public ResponseEntity tratarErroAcessoNegado() { | |
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Acesso negado"); | |
} | |
@ExceptionHandler(Exception.class) | |
public ResponseEntity tratarErro500(Exception ex) { | |
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Erro: " +ex.getLocalizedMessage()); | |
} | |
private record DadosErroValidacao(String campo, String mensagem) { | |
public DadosErroValidacao(FieldError erro) { | |
this(erro.getField(), erro.getDefaultMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment