簡體   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