Performance: @ExceptionHandler in controllers
This affects server response time and error handling efficiency, indirectly impacting user experience by controlling error response speed and page stability.
@Controller public class MyController { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleAllExceptions(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Custom error message"); } }
public String handleRequest() {
try {
// controller logic
} catch (Exception e) {
return "errorPage";
}
}| Pattern | Server Processing | Code Duplication | Response Consistency | Verdict |
|---|---|---|---|---|
| Try-catch in each controller method | High - repeated handling | High - duplicated code | Low - inconsistent | [X] Bad |
| Centralized @ExceptionHandler method | Low - single handler | Low - centralized code | High - consistent | [OK] Good |
@ExceptionHandler in a Spring Boot controller?NullPointerException occurs?@RestController
public class MyController {
@GetMapping("/test")
public String test() {
throw new NullPointerException("Null error");
}
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleNullPointer() {
return "Null pointer error handled";
}
}@RestController
public class DemoController {
@GetMapping("/demo")
public String demo() {
throw new IllegalArgumentException("Invalid argument");
}
@ExceptionHandler(NullPointerException.class)
public String handleNull() {
return "Null error";
}
}/demo endpoint is called?RuntimeException for all controllers and returns a JSON error message with HTTP status 500. Which approach correctly achieves this?Pass the test and this pattern moves unknown