Skip to content

Instantly share code, notes, and snippets.

@vitorgonzaga
Created March 28, 2023 12:18
Show Gist options
  • Save vitorgonzaga/5aefe4fd6fdca186eb320ff90be8c427 to your computer and use it in GitHub Desktop.
Save vitorgonzaga/5aefe4fd6fdca186eb320ff90be8c427 to your computer and use it in GitHub Desktop.
TratadorDeErros
@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