【发布时间】:2018-12-22 05:19:31
【问题描述】:
当我的请求出现问题并且我尝试使用@NotEmpty约束消息属性返回错误消息时,我需要有自己的错误响应正文,
这是我的类,它使用我需要的正文返回错误消息:
package c.m.nanicolina.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public class CustomResponseEntityExceptionHandler {
@ExceptionHandler(value = {MissingServletRequestParameterException.class})
public ResponseEntity<ApiError> handleConflict(MissingServletRequestParameterException ex, WebRequest request) {
ApiError apiError = new ApiError(ex.getMessage(), ex.getMessage(), 1000);
return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);
}
}
有了这个CustomResponseEntityExceptionHandler,我可以在出现验证错误时返回我自己的响应正文。
我现在正在尝试从验证约束中获取消息。
这是我的控制器,带有NotEmpty 约束:
package c.m.nanicolina.controllers;
import c.m.nanicolina.models.Product;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotEmpty;
@RestController
public class MinimumStockController {
@RequestMapping(value = "/minimumstock")
public Product product(
@RequestParam(value = "product.sku") @NotEmpty(message = "Product.sku cannot be empty") String sku,
@RequestParam(value = "stock.branch.id") String branchID) {
return null;
}
}
在我的例外情况下,我找不到获取该消息 Product.sku cannot be empty 并将其显示在我的错误响应中的方法。
我还检查了 MissingServletRequestParameterException 类,有一个方法 getMessage 返回默认消息。
【问题讨论】:
标签: java validation spring-boot exception-handling query-parameters