Pular para o conteúdo principal

Capítulo 1: Tratamento de Exceções

Introdução​

Exceções são o mecanismo do Java para sinalizar erros. Utilizá-las corretamente é essencial para criar aplicações robustas e fáceis de manter.


🎯 Objetivos do Capítulo​

Ao final deste capítulo, você saberá:

  1. ✅ Diferenciar Checked e Unchecked exceptions
  2. ✅ Criar exceções personalizadas
  3. ✅ Organizar uma hierarquia de exceções
  4. ✅ Aplicar boas práticas

1. Lembrete: Hierarquia de Exceções no Java​

Throwable
├── Error (não capturar)
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception
├── Checked Exceptions (devem ser declaradas)
│ ├── IOException
│ └── SQLException
└── RuntimeException (Unchecked)
├── NullPointerException
├── IllegalArgumentException
└── Suas exceções personalizadas

2. Checked vs Unchecked​

Checked Exceptions​

// Devem ser declaradas com throws ou capturadas
public void readFile(String path) throws IOException {
Files.readString(Path.of(path)); // IOException possível
}

// Ou
public void readFile(String path) {
try {
Files.readString(Path.of(path));
} catch (IOException e) {
// Tratar o erro
}
}

Quando usar? Erros recuperáveis (arquivo ausente, rede).

Unchecked Exceptions (RuntimeException)​

// Não precisa declarar
public User findById(Long id) {
if (id == null) {
throw new IllegalArgumentException("ID cannot be null");
}
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}

Quando usar? Erros de programação, violações de contrato.

No Spring Boot: Prefira Unchecked​

// ❌ Difícil de usar
public User findById(Long id) throws UserNotFoundException {
// ...
}

// ✅ Mais fluido
public User findById(Long id) {
// Lança uma RuntimeException se não encontrado
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}

3. Criando Exceções Personalizadas​

Exceção Simples​

public class UserNotFoundException extends RuntimeException {

public UserNotFoundException(Long id) {
super("User not found with ID: " + id);
}

public UserNotFoundException(String message) {
super(message);
}
}

Exceção com Dados Adicionais​

@Getter
public class ResourceNotFoundException extends RuntimeException {

private final String resourceType;
private final Object resourceId;

public ResourceNotFoundException(String resourceType, Object resourceId) {
super(String.format("%s not found with ID: %s", resourceType, resourceId));
this.resourceType = resourceType;
this.resourceId = resourceId;
}
}

// Uso
throw new ResourceNotFoundException("User", 123L);
throw new ResourceNotFoundException("Product", "SKU-001");

Exceção com Código de Erro​

@Getter
public class BusinessException extends RuntimeException {

private final String errorCode;
private final Map<String, Object> details;

public BusinessException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
this.details = new HashMap<>();
}

public BusinessException(String errorCode, String message, Map<String, Object> details) {
super(message);
this.errorCode = errorCode;
this.details = details;
}
}

// Uso
throw new BusinessException(
"INSUFFICIENT_BALANCE",
"Insufficient balance for withdrawal",
Map.of("requested", 500, "available", 100)
);

4. Hierarquia de Exceções de Negócio​

Estrutura Recomendada​

// Exceção base para a aplicação
public abstract class ApplicationException extends RuntimeException {

private final String errorCode;

protected ApplicationException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}

protected ApplicationException(String errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}

public String getErrorCode() {
return errorCode;
}
}

Exceções Específicas​

// Recurso não encontrado (→ 404)
public class ResourceNotFoundException extends ApplicationException {

public ResourceNotFoundException(String resourceType, Object id) {
super("RESOURCE_NOT_FOUND",
String.format("%s with ID %s not found", resourceType, id));
}
}

// Validação falhou (→ 400)
public class ValidationException extends ApplicationException {

private final List<FieldError> errors;

public ValidationException(List<FieldError> errors) {
super("VALIDATION_FAILED", "Validation failed");
this.errors = errors;
}
}

// Conflito (→ 409)
public class ConflictException extends ApplicationException {

public ConflictException(String message) {
super("CONFLICT", message);
}
}

// Não autorizado (→ 403)
public class ForbiddenException extends ApplicationException {

public ForbiddenException(String message) {
super("FORBIDDEN", message);
}
}

// Erro de negócio (→ 422)
public class BusinessRuleException extends ApplicationException {

public BusinessRuleException(String code, String message) {
super(code, message);
}
}

Diagrama​

ApplicationException
├── ResourceNotFoundException → 404
├── ValidationException → 400
├── ConflictException → 409
├── ForbiddenException → 403
├── BusinessRuleException → 422
└── TechnicalException → 500

5. Exemplos de Uso​

Em um Service​

@Service
@RequiredArgsConstructor
public class UserService {

private final UserRepository userRepository;

public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", id));
}

public User create(UserRequest request) {
// Verificar unicidade
if (userRepository.existsByEmail(request.getEmail())) {
throw new ConflictException("Email already in use: " + request.getEmail());
}

// Criar o usuário
User user = new User();
user.setEmail(request.getEmail());
user.setName(request.getName());
return userRepository.save(user);
}

public void delete(Long id) {
User user = findById(id); // Lança ResourceNotFoundException se não encontrado

if (user.hasActiveOrders()) {
throw new BusinessRuleException(
"CANNOT_DELETE_USER_WITH_ORDERS",
"Cannot delete user with active orders"
);
}

userRepository.delete(user);
}
}

Em um Controller (sem tratamento centralizado)​

@RestController
@RequestMapping("/api/users")
public class UserController {

@GetMapping("/{id}")
public ResponseEntity<User> getById(@PathVariable Long id) {
try {
User user = userService.findById(id);
return ResponseEntity.ok(user);
} catch (ResourceNotFoundException e) {
return ResponseEntity.notFound().build();
}
}
}

Problema: Repetição do try-catch em cada método!

Solução: @ControllerAdvice (próximo capítulo)


6. Boas Práticas​

✅ O que Fazer​

// 1. Nomear claramente
public class InsufficientStockException extends BusinessRuleException { }
public class PaymentDeclinedException extends BusinessRuleException { }

// 2. Incluir o contexto
throw new ResourceNotFoundException("Product", productId);

// 3. Usar códigos de erro
throw new BusinessRuleException("ORDER_LIMIT_EXCEEDED", "...");

// 4. Encadear as causas
try {
externalService.call();
} catch (ExternalServiceException e) {
throw new TechnicalException("External service failed", e);
}

❌ O que Evitar​

// 1. Exceções genéricas
throw new Exception("Something went wrong"); // ❌

// 2. Mensagens vazias
throw new RuntimeException(); // ❌

// 3. Catch and ignore
try {
riskyOperation();
} catch (Exception e) {
// Silencioso - ❌ NUNCA!
}

// 4. Exceções para fluxo normal
try {
user = findById(id);
} catch (UserNotFoundException e) {
user = createUser(id); // ❌ Use Optional em vez disso
}

Padrão: Optional vs Exception​

// Para "pode não existir"
public Optional<User> findByEmail(String email) {
return userRepository.findByEmail(email);
}

// Para "DEVE existir"
public User getById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", id));
}

7. Exceções Nativas do Spring Boot​

ResponseStatusException​

@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_FOUND,
"User not found: " + id
));
}

Vantagem: Simples, não precisa de @ControllerAdvice
Desvantagem: Menos flexível, sem formato personalizado

@ResponseStatus em Exceção​

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super("User not found: " + id);
}
}

Vantagem: Automático
Desvantagem: Formato de resposta padrão do Spring


8. Resumo​

Tipos de Exceções​

TipoHerançaUso
CheckedExceptionErros recuperáveis
UncheckedRuntimeExceptionErros de negócio, programação

Hierarquia Recomendada​

ApplicationException (abstract)
├── ResourceNotFoundException (404)
├── ValidationException (400)
├── ConflictException (409)
├── BusinessRuleException (422)
└── TechnicalException (500)

Checklist​

✅ Exceções herdam de RuntimeException
✅ Mensagens claras e informativas
✅ Códigos de erro para a API
✅ Contexto incluído (ID, tipo de recurso)
✅ Causas encadeadas para depuração

🎯 Próximo Passo​

Você já sabe criar exceções. Agora, vamos aprender a tratá-las globalmente com @ControllerAdvice.

➡️ Capítulo 2: @ControllerAdvice


⬅️ Voltar ao Módulo 10