Q1. How do you handle exceptions in a REST API?
Use
You can return a custom error response with appropriate HTTP status.
Example:
@ExceptionHandler in controllers or globally with @ControllerAdvice.You can return a custom error response with appropriate HTTP status.
Example:
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFound(ResourceNotFoundException ex) { ... }
Q2. What is @ControllerAdvice?
It can contain
@ControllerAdvice is a specialization of @Component that allows you to handle exceptions across the whole application.It can contain
@ExceptionHandler, @InitBinder, and @ModelAttribute methods that apply to all controllers.Q3. How do you return appropriate HTTP status codes?
Use
Alternatively, you can set status via
Example:
@ResponseStatus annotation on exception classes or on handler methods.Alternatively, you can set status via
ResponseEntity.Example:
return ResponseEntity.status(HttpStatus.CREATED).body(user);
Q4. What is ResponseEntity?
It gives you full control over the response.
You can use it to return custom status and headers in REST endpoints.
ResponseEntity is a class that represents the entire HTTP response: status code, headers, and body.It gives you full control over the response.
You can use it to return custom status and headers in REST endpoints.
Q5. How do you handle validation errors in REST?
When using
You can handle it globally with
@Valid on @RequestBody, a MethodArgumentNotValidException is thrown.You can handle it globally with
@ExceptionHandler and collect field errors into a structured response.