0

I'm developing a RESTful api using spring boot 2 and trying to upload a file with limit set in the yml file as servlet.multipart.max-file-size=2MB.

As per my requirement any file size uploaded above 2MB need to inserted into the database with the request information (getUser()) and the exception. I'm able to generate the exception message using @ExceptionHandler but i do not get the request information (getUser()). please advise.

I tried with WebRequest webRequest on the rest controller with webRequest.setAttribute but I get Null in the @ExceptionHandler.

My Controller and Controller advice:

@PostMapping(path = "/sendEmail")
    public ResponseEntity<EmailVO> sendEmail(@RequestPart(value = "file", required = false) MultipartFile[] uploadfile,
            @RequestPart EmailVO emailVO,WebRequest webRequest, HttpServletRequest httprequest) {
        webRequest.setAttribute("emailVO", emailVO, RequestAttributes.SCOPE_REQUEST);
        EmailVO emailVO = myService.sendEmail(emailVO, uploadfile);
        return new ResponseEntity<>(emailVO, HttpStatus.OK);
    }


@ExceptionHandler(Exception.class)
    public ExceptionResponse handleException(final Exception ex, final HttpServletRequest httprequest,WebRequest webrequest) {
        if (ex instanceof MaxUploadSizeExceededException) { 
            EmailVO  emailVO  = (EmailVO) webrequest.getAttribute(EmailVO, RequestAttributes.SCOPE_REQUEST);
            return new ExceptionResponse("Exceeds the limit for user "+emailVO.getUser,ex.getClass().getSimpleName(), httprequest.getRequestURI(),"Failure");
        } 
    }

I'm unable to get the emailVO.getUser which is coming from the request controller

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
Rabikatha
  • 249
  • 5
  • 9
  • Do you want to know the user who uploaded bigger file ? – Sambit May 17 '19 at 16:15
  • No.. what ever json object i sent in the POST request i want in the controller advice so that i can insert into the database about the request and the error i got on the maxuploadsizeexceededlimit – Rabikatha May 18 '19 at 04:14
  • You can wrap EmailVO object inside the Exception object. Create separate method called handleMaxSizeUploadException(...). – Sambit May 18 '19 at 06:43
  • @Sambit i'm not able to get what your trying to explain me, do u want to have another method in handleMaxSizeUploadException() in controller advise but how do i wrap the VO object in exception object? Please elaborate. Thank you – Rabikatha May 25 '19 at 03:59

0 Answers0