HttpMediaTypeNotAcceptableException
是 Spring 框架中的一个异常,表示客户端请求的媒体类型(如 Content-Type
或 Accept
头)不被服务器支持。这个异常通常发生在 RESTful API 中,当客户端请求的资源无法以客户端期望的格式返回时。
RuntimeException
。HttpMediaTypeNotAcceptableException
不会被同一控制器中的 @ExceptionHandler
捕获的原因通常是因为 Spring 的异常处理机制默认情况下不会在同一个控制器内部捕获这种类型的异常。Spring 会将这种异常视为全局异常,并尝试在更高层次的异常处理器中处理它。
为了捕获并处理这个异常,可以采取以下几种方法:
@ControllerAdvice
和 @ExceptionHandler
注解创建一个全局异常处理器。import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
public ResponseEntity<String> handleHttpMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex) {
return new ResponseEntity<>("Media type not acceptable", HttpStatus.NOT_ACCEPTABLE);
}
}
@ExceptionHandler
注解。import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
@RestController
public class MyController {
@GetMapping("/example")
public String example() {
// 模拟抛出异常
throw new HttpMediaTypeNotAcceptableException("Example exception");
}
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
public ResponseEntity<String> handleHttpMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex) {
return new ResponseEntity<>("Media type not acceptable", HttpStatus.NOT_ACCEPTABLE);
}
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
@RestController
public class MyController {
@GetMapping(value = "/example", produces = MediaType.APPLICATION_JSON_VALUE)
public String example() {
return "{\"message\": \"Hello, World!\"}";
}
}
通过以上方法,可以有效捕获并处理 HttpMediaTypeNotAcceptableException
异常,确保 API 的健壮性和用户体验。
领取专属 10元无门槛券
手把手带您无忧上云