Spring Boot:如何处理@RequestParam引起的400错误?

时间:2016-03-25 06:41:42

标签: spring-boot

public String(@RequestParam Integer id) {
// ...
}

如果在当前请求中找不到id参数,我将获得400状态代码,其响应体为空。现在我想为这个错误返回JSON字符串,我该怎么做呢?

PS:我不想使用@RequestParam(required = false)

3 个答案:

答案 0 :(得分:0)

尝试使用@PathVariable,希望它符合您的要求。

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(@PathVariable("id") long id) {
    System.out.println("Fetching User with id " + id);
    User user = userService.findById(id);
    if (user == null) {
        System.out.println("User with id " + id + " not found");
        return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<User>(user, HttpStatus.OK);
}

答案 1 :(得分:0)

我做到了。 只需覆盖您自己的handleMissingServletRequestParameter()类中的ResponseEntityExceptionHandler方法。

@Override
    protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        log.warn("miss Request Param");

        return new ResponseEntity<>(new FoxResponse(ErrorCode.ARG_INVALID), status);
    }

答案 2 :(得分:0)

只是有同样的问题,但引发的异常是MethodArgumentTypeMismatchException。使用@ControllerAdvice错误处理程序,可以检索有关@RequestParam错误的所有数据。这是对我有用的完整课程

@ControllerAdvice
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class ControllerExceptionHandler {

  @ExceptionHandler(value = {MethodArgumentTypeMismatchException.class})
  @ResponseStatus(value = HttpStatus.BAD_REQUEST)
  @ResponseBody
  public Map<String, String> handleServiceCallException(MethodArgumentTypeMismatchException e) {
    Map<String, String> errMessages = new HashMap<>();
    errMessages.put("error", "MethodArgumentTypeMismatchException");
    errMessages.put("message", e.getMessage());
    errMessages.put("parameter", e.getName());
    errMessages.put("errorCode", e.getErrorCode());
    return errMessages;
  }

}