【发布时间】:2020-03-01 23:13:00
【问题描述】:
我已经编写了一个测试服务,它只将文件标题作为参数,即 testfile.jpg.. 所有这一切都是用自定义异常消息抛出我的自定义异常。当我使用 'testfile' 作为参数时,它工作正常.. 给出 400 错误状态代码。如果我使用“testfile.jpg”,它似乎不喜欢其中的扩展名,错误状态代码会以 500 内部错误的形式返回。
有人知道我可以做些什么来解决这个问题吗?所以它在使用带有扩展名的文件时显示正确的 400 错误状态代码(即 testfile.jpg)?
控制器:
@ApiOperation("Tests")
@RequestMapping(value = {"/testingURL/{test}"}, method = RequestMethod.GET, produces = {MediaType.IMAGE_PNG_VALUE,MediaType.IMAGE_JPEG_VALUE})
@ResponseBody
public ResponseEntity<byte[]> getTestingURL(@PathVariable String test) throws Exception{
return assetStoreService.test(test);
}
服务方式:
public ResponseEntity<byte[]> test(final String test) throws CustomTestException{
if(!test.isEmpty()){
exceptionThrower();
}
TestImage testImage = new TestImage();
return getResponseEntity(testImage);
}
异常抛出者:
private void exceptionThrower() throws CustomTestException {
throw new CustomTestException("blahbah");
}
CustomTestException.java:
public class CustomTestException extends Exception {
public CustomTestException(String errorMessage) {
super(errorMessage);
}
}
异常处理程序:
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(CustomTestException.class)
protected ResponseEntity handleCustomTestException (HttpServletRequest request, CustomTestException ex){
request.removeAttribute(
HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
TestError testError = new TestError(HttpStatus.BAD_REQUEST,ex.getMessage(),ex);
return new ResponseEntity<Object>(testError, new HttpHeaders(), testError.getStatus());
}
下面的位,是删除接受的返回类型(图像),以便它可以返回异常 json 对象响应:
request.removeAttribute(
HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
【问题讨论】:
标签: java spring-boot exception