xxxxxxxxxx
@RestController
public class MyController {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
// Custom logic for exception handling
// You can handle specific exception types separately by creating additional methods with @ExceptionHandler annotation
// Example response
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
}
@GetMapping("/example")
public ResponseEntity<String> example() throws Exception {
// Some business logic that throws an exception
throw new Exception("Something went wrong");
}
}
xxxxxxxxxx
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
// Handle the exception and return an appropriate response
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred: " + ex.getMessage());
}
// You can add multiple methods with @ExceptionHandler for different types of exceptions
@ExceptionHandler(YourCustomException.class)
public ResponseEntity<String> handleCustomException(YourCustomException ex) {
// Handle YourCustomException and return a specific response
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Bad Request: " + ex.getMessage());
}
// Add more exception handler methods as needed
}