Spring Boot Interview Questions
Spring Boot
Java
BackendWeb DevelopmentQuestion 12
How do you handle exceptions in a Spring Boot application?
Answer:
Handling exceptions in a Spring Boot application is an important aspect of building robust and user-friendly applications. Spring Boot provides several mechanisms to handle exceptions effectively. Here are the primary ways to handle exceptions:
1. Global Exception Handling with @ControllerAdvice
@ControllerAdvice
is a powerful feature in Spring Boot that allows you to handle exceptions across the whole application, not just to an individual controller. This makes it easier to manage and centralize exception handling.
Example:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleGlobalException(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
In this example:
@ControllerAdvice
is used to define a global exception handler.@ExceptionHandler
methods handle specific exceptions (ResourceNotFoundException
) and general exceptions (Exception
).- The
ErrorDetails
class is a custom error response object that contains details about the error.
2. Custom Exception Class
Creating custom exceptions allows you to provide meaningful exception handling specific to your application's needs.
Example:
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message) {
super(message);
}
}
3. Using @ResponseStatus
Annotation
You can use the @ResponseStatus
annotation on custom exceptions to specify the HTTP status code that should be returned when the exception is thrown.
Example:
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message) {
super(message);
}
}
In this example, when a ResourceNotFoundException
is thrown, it will automatically return a 404 Not Found status.
4. Controller-Specific Exception Handling
You can also handle exceptions at the controller level using the @ExceptionHandler
annotation within a specific controller.
Example:
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
@RestController
public class MyController {
@GetMapping("/resource/{id}")
public ResponseEntity<Resource> getResource(@PathVariable Long id) {
// Logic to retrieve resource
throw new ResourceNotFoundException("Resource not found with id " + id);
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException ex) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), "Resource Not Found");
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
}
In this example, ResourceNotFoundException
is handled within the MyController
class, returning a specific response for that exception.
5. Custom Error Response
Creating a custom error response class to provide structured error information to clients.
Example:
import java.util.Date;
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
// Getters and setters
}
6. Enabling Detailed Error Messages
For development purposes, you can enable detailed error messages in the application.properties
file.
server.error.include-message=always
server.error.include-binding-errors=always
Summary
- Global Exception Handling with
@ControllerAdvice
: Centralizes exception handling across the entire application. - Custom Exception Class: Allows meaningful, application-specific exception handling.
- Using
@ResponseStatus
: Specifies the HTTP status code for custom exceptions. - Controller-Specific Exception Handling: Handles exceptions within a specific controller.
- Custom Error Response: Provides structured error information to clients.
- Enabling Detailed Error Messages: Configures detailed error responses for development purposes.
Using these techniques, you can effectively handle exceptions in your Spring Boot application, providing clear, consistent error responses and improving the overall robustness and user experience of your application.