【问题标题】:500 error with .jpg when using custom exception handling with spring boot?使用 Spring Boot 的自定义异常处理时 .jpg 出现 500 错误?
【发布时间】: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


    【解决方案1】:

    这是作为最佳实践的内容协商的一部分。如果您仍想使用扩展名,请在 application.properties 文件中尝试此操作

    spring.mvc.contentnegotiation.favor-path-extension=true

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2021-07-10
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 2016-07-11
      • 2018-01-04
      相关资源
      最近更新 更多