Java Spring - how to handle missing required request parameters

前端 未结 3 913
再見小時候
再見小時候 2021-02-01 16:53

Consider the following mapping:

@RequestMapping(value = \"/superDuperPage\", method = RequestMethod.GET)
public String superDuperPage(@RequestParam(value = \"som         


        
3条回答
  •  情话喂你
    2021-02-01 17:19

    An alternative

    If you use the @ControllerAdvice on your class and if it extends the Spring base class ResponseEntityExceptionHandler. A pre-defined function has been created on the base class for this purpose. You have to override it in your handler.

        @Override
    protected ResponseEntity handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String name = ex.getParameterName();
        logger.error(name + " parameter is missing");
    
        return super.handleMissingServletRequestParameter(ex, headers, status, request);
    }
    
    
    

    This base class is very useful, especially if you want to process the validation errors that the framework creates.

    提交回复
    热议问题