# Re:0 - Starting Life in Backend - Day4
2025-07-16
3 min read
seal
若是月亮还没来
路灯也可照窗台
照着白色的山茶花微微开
若是晨风还没来
晚风也可吹入怀
吹着那一地树影温柔摇摆
Level 6: Exception handling and error prompts
Target: Implement a unified exception handling mechanism to provide friendly error prompts for the front end.
Solution
To solve this problem, I choose to create a new code package —— exception
In this code package, I divided it into two parts below:
- Custom Exceptions
- Unified exception collector
Custom Exceptions
package com.example.demo2.exception;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
//The @ResponseStatus annotation can automatically set the HTTP response status code when an exception is thrown
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message){
super(message);
}
public UserNotFoundException(Long id){
super("User with id " + id + " not found");
}
}
This class extends normal exception , and use super method to create a custom exception
Unified exception collector
package com.example.demo2.exception;
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;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
//The @ControllerAdvice annotation indicates that this is a global exception handler
// It will intercent all exceptions thrown by @Controller
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<Map<String,Object>> handleUserNotFoundException(
UserNotFoundException ex, WebRequest request){
Map<String,Object> errorDetails = new HashMap<>();
errorDetails.put("timestamp", LocalDateTime.now());
errorDetails.put("status", HttpStatus.NOT_FOUND.value());
errorDetails.put("error", "User not found");
errorDetails.put("message", ex.getMessage());
errorDetails.put("path1", request.getContextPath());
errorDetails.put("path2", request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGlobalException(
Exception ex, WebRequest request){
Map<String,Object> errorDetails = new HashMap<>();
errorDetails.put("timestamp", LocalDateTime.now());
errorDetails.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
errorDetails.put("error", "Internal server error");
errorDetails.put("message", ex.getMessage());
errorDetails.put("path2", request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Here devided exceptions into two classes —— UserNotFound and Normal Exception