在Spring Boot中,可以通过以下几种方式来处理错误和异常:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());
}
}
@RestController
public class MyController {
@RequestMapping("/test")
public String test() {
throw new RuntimeException("Test exception");
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());
}
}
@ControllerAdvice
public class GlobalErrorHandler {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found: " + e.getMessage());
}
}
@Controller
public class MyErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError() {
return "error";
}
@Override
public String getErrorPath() {
return "/error";
}
}
通过以上方式,可以灵活地处理Spring Boot应用中的错误和异常,提高应用的健壮性和用户体验。