Spring Boot Global Exception Handling

Use a global exception handler to intercept business exceptions and return a consistent error structure.

java
1@RestControllerAdvice2public class Global Exception Handler {34  @Exception Handler(BusinessException.class)5  public API Response handle business(BusinessException ex) {6    return API Response.failed(ex.Get Code(), ex.Get Message());7  }89  @Exception Handler(Exception.class)10  public API Response Handle Other(Exception ex) {11    return API Response.failed(500, Server is busy. Please try again later.);12  }13}

Key Points

  • Exceptions thrown in the controller are matched against more specific exception types first.
  • Do not expose stack traces in fallback branches; return a readable message instead.

Usage suggestions

Run the copied code in a local sample project first to verify expected behavior, then adapt the naming and structure to your business needs. Pasting directly into a large project can cause you to overlook contextual differences.