Sobes.tech
Junior — Middle

How to properly handle and log errors in a project containing multiple REST controllers, each responsible for CRUD operations for different entities?

sobes.tech AI

Answer from AI

Proper error handling and logging in a project with many REST controllers include the following practices:

  • Centralized error handling: use a global exception handler (e.g., @ControllerAdvice in Spring) to avoid duplicating code in each controller.
  • Standardized error response format: return a unified format to the client with an error code, message, and, if necessary, details.
  • Error logging with context: log not only the error message but also request information, parameters, user details, and stack traces.
  • Separation of logging levels: for example, WARN for expected errors (e.g., validation), ERROR for critical exceptions.

Example of a global handler in Spring Boot:

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(EntityNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(EntityNotFoundException ex) {
        logger.warn("Entity not found: {}", ex.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
            .body(new ErrorResponse("NOT_FOUND", ex.getMessage()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleException(Exception ex) {
        logger.error("Unexpected error", ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(new ErrorResponse("INTERNAL_ERROR", "An internal server error occurred"));
    }
}

class ErrorResponse {
    private String code;
    private String message;

    // constructors, getters, setters
}

This approach simplifies maintenance and improves the quality of logging and error handling throughout the project.

How to properly handle and log errors in a project… - sobes.tech