Loading...
44

I want to handle all exceptions in one place in my Spring Boot application instead of using try-catch in every controller method.

What's the best practice for global exception handling that returns proper JSON error responses?

I want to handle:

    1. Validation errors
    2. Resource not found
    3. Database errors
    4. Custom business exceptions

asked 4 days ago

Log in to add a comment.

1 Answer

41

Use @ControllerAdvice for global exception handling. Here's a complete solution:

Custom Exceptions:
__CODEBLOCK0

*Global Exception Handler:*
CODEBLOCK1__java
@Data
@AllArgsConstructor
public class ErrorResponse {
private int status;
private String message;
private LocalDateTime timestamp;
}
```

answered 3 days ago
Log in to answer this question.
Question Stats
Asked: 4 days ago
Views: 1.7k
Active: 1 day ago
Related Tags