Unlock Spring’s Power: Global Exception Handling, Custom Interceptors, and Thread‑Local Scopes
Explore Spring’s extensibility by mastering global exception handling with @RestControllerAdvice, creating custom MVC interceptors, accessing the container via BeanFactoryAware, importing configurations, adding startup logic, modifying BeanDefinitions, using initialization callbacks, and defining a thread‑local custom scope for per‑thread bean instances.
1. Global Exception Handling
When an API throws an exception, the raw stack trace is exposed to the user. Example controller code:
@RequestMapping("/test")
@RestController
public class TestController {
@GetMapping("/division")
public String division(@RequestParam("a") int a, @RequestParam("b") int b) {
return String.valueOf(a / b);
}
}Calling 127.0.0.1:8080/test/division?a=10&b=0 returns a detailed error page, which is a poor user experience. Using a global exception handler solves this:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
if (e instanceof ArithmeticException) {
return "params error";
}
return "Internal server exception";
}
}Now the user sees a friendly message "params error".
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
