繁体   English   中英

使用 spring 启动的自定义异常处理时,.jpg 出现 500 错误?

[英]500 error with .jpg when using custom exception handling with spring boot?

我已经编写了一个测试服务,它只将文件标题作为参数,即 testfile.jpg.. 所有这一切都是用自定义异常消息抛出我的自定义异常。 当我使用“testfile”作为参数时,它工作正常.. 给出 400 错误状态代码。 如果我使用“testfile.jpg”,它似乎不喜欢其中的扩展名,错误状态代码会以 500 内部错误的形式返回。

有谁知道我能做些什么来解决这个问题? 所以它在使用带有扩展名的文件(即testfile.jpg)时显示正确的400错误状态代码?

controller:

    @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 object 响应:

    request.removeAttribute(
            HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM