Technical Medium Software Engineer Backend Full Stack

How do you handle exceptions globally in a Spring Boot REST API?

Practise this question with AI feedback

Record your spoken answer or type your response to receive immediate scoring and STAR improvements.

💡 Suggested Approach & Sample Answer

Approach: centralise error handling with @RestControllerAdvice so every controller returns consistent, safe error responses.

How it works:
- Create a class annotated with @RestControllerAdvice.
- Add @ExceptionHandler methods for specific exception types, for example ResourceNotFoundException mapped to 404 and MethodArgumentNotValidException (bean validation failures) mapped to 400 with field errors.
- Add a fallback handler for Exception that logs the error with a correlation id and returns a generic 500 message without stack traces.

Response format:
- Use a consistent body. Spring 6 / Boot 3 support RFC 7807 ProblemDetail (type, title, status, detail, instance), enabled with spring.mvc.problemdetails.enabled=true or by returning ProblemDetail from handlers.

Good practices:
- Never leak internal messages, SQL or stack traces to clients.
- Map domain exceptions to precise HTTP codes (409 conflict, 422 validation, 403 forbidden).
- Log at the right level: client errors at warn or info, server errors at error.
- Test handlers with @WebMvcTest and MockMvc.

🎯 What Interviewers Listen For

How would you answer this in a real interview?

Use our free AI mock practice tool to test your response, analyze speaking pacing, and refine your STAR structure.

🔗 Related Technical Questions