1

An error occurs when I upload the file size bigger than the set value. I want to catch this exception and return it to the browser.The e.getCause().getMessage() has a value , but not successfully return to browser. Normally, a piece of json will be displayed on the browser. handleFileFormatException is no problem, but handleIllegalStateException can't display any message and occurs "Unable to access this site" on the browser.The paths are all shown:localhost:8080. These two methods are almost the same, the difference is that FileFormatExceptio is my defined exception class, but IllegalStateException is not. Why didn't it return json entity to the browser. I don't know what to do.Who can help me? Thank you!

application.properties: application.properties

@ExceptionHandler @ExceptionHandler

ExceptionResponse

public class ExceptionResponse {

private String message;
private Integer code;


public ExceptionResponse(Integer code, String message){
    this.message = message;
    this.code = code;
}

public static ExceptionResponse create(Integer code, String message){
    return new ExceptionResponse(code, message);
}

public Integer getCode() {
    return code;
}
public String getMessage() {
    return message;
}

}

Console warning, NO error

 2017-07-31 17:10:50.388  WARN 10940 --- [nio-8080-exec-4] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (42990730) exceeds the configured maximum (10485760)

Browser press F12 enter image description here

enter image description here

Controller

@Controller
public class FileUploadController {

    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }


   @GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {

        model.addAttribute("files", storageService
                .loadAll()
                .map(path ->
                        MvcUriComponentsBuilder
                                .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                                .build().toString())
                .collect(Collectors.toList()));

        return "index";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = storageService.loadAsResource(filename);
        return ResponseEntity
                .ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                .body(file);
    }

    @PostMapping("/")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes){
        storageService.store(file);
        redirectAttributes.addFlashAttribute("message",
                "upload success! " + file.getOriginalFilename() + "!");
        return "redirect:/";
    }

getStatus

private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
yongguangl
  • 87
  • 2
  • 11
  • Try to catch `org.springframework.web.multipart.MultipartException` instead of `java.lang.IllegalStateException` . – Akli REGUIG Jul 31 '17 at 08:14
  • @ResponseBody @ExceptionHandler(MultipartException.class) public String handleSizeExceededException(HttpServletRequest request,MultipartException ex) { return ex.getMessage(); } – yongguangl Jul 31 '17 at 08:27
  • But the browser still shows no response errors – yongguangl Jul 31 '17 at 08:28
  • Oh, i didn't understood what was the problem, now i do. can you show us the class `ExceptionResponse` ? can you check using dev tools from your browser a tell us what is the app really returning. (status,headers,content) – Akli REGUIG Jul 31 '17 at 08:39
  • Ok! I have updated some information you need,You can have a look – yongguangl Jul 31 '17 at 09:33
  • ok. you are doing this through GET, a POST is better for what you are doing. And your Controller is responding with 200 ok. Can you show you controller method code too . – Akli REGUIG Jul 31 '17 at 09:49
  • OK! This is an official (Springboot)example – yongguangl Jul 31 '17 at 10:04
  • After uploading the file, the corresponding hyperlink will be displayed, and we can click the download – yongguangl Jul 31 '17 at 10:05
  • ok. i'm trying to reproduce it . Can you try clear your cache, use a `CUrl` or another browser. – Akli REGUIG Jul 31 '17 at 10:51
  • I found some similar problems on the Internet. but I didn't succeed. You can look at these links and maybe get a better understanding of my problem. https://stackoverflow.com/questions/23856254/how-to-nicely-handle-file-upload-maxuploadsizeexceededexception-with-spring-secu – yongguangl Jul 31 '17 at 11:56
  • A few days ago I had sent a similar problem on "Stack Overflow", but not solved, Just soon, one of the people gave me A reply, and the problem solved.Thank you very much for your help! – yongguangl Jul 31 '17 at 12:56
  • ok. glad it works now. i saw the response you had. The code from the post works because it returns a ResponseEntity with a status code. Your code doesn't set the status code and this is the reason why it doesn't work. Check my answer bellow to make your code work only by adding 1 line :) . – Akli REGUIG Jul 31 '17 at 13:03
  • Kindly accept my answer if it worked for you too. Thanks – Akli REGUIG Jul 31 '17 at 17:51
  • I can't believe it! Just today, I ran the program and found that there was no problem, but there was a problem at yesterday, and I did not make any changes.It's amazing.Too amazing! – yongguangl Aug 01 '17 at 02:49

1 Answers1

0

You are missing the part where you set the http response status code when the exception is handled by your exception handler.

  • Add @ResponseStatus(value= HttpStatus.BAD_REQUEST) to your method.

or

  • Add HttpServletResponse response to the method arguments list and call response.setStatus(HttpStatus.BAD_REQUEST.value()); before returning your object.
Akli REGUIG
  • 552
  • 4
  • 13
  • I already have it,“HttpStatus status = getStatus(request);”But yesterday it didn't return anything, and the same code can be returned today, I don't know why,too amazing! So your explanation is also correct, I will accept, thank you! – yongguangl Aug 01 '17 at 02:54
  • I don't know what the method `getStatus` was doing in your code. But you were trying to extract an http status code from the request (i don't think this returns anything). The thing you need to do is to update the `HttpServletResponse` (response and not request) http status code value to really affect the http response your application is sending back to the browser. – Akli REGUIG Aug 01 '17 at 07:50
  • Ok, I updated my getStatus() method. Although I did't fully understand, but the program is no problem now, so I think this method should be also no problem. you can have a look. – yongguangl Aug 01 '17 at 10:15