@RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
public String saveOrUpdate(HttpServletResponse response, @RequestBody Order order){
CodeMsg result = null;
try {
result = orderService.saveOrUpdate(order);
} catch (Exception e) {
logger.error("save failed.", e);
return this.renderString(response, CodeMsg.error(e.getMessage()));
}
return this.renderString(response, result);
}
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public CodeMsg messageNotReadable(HttpMessageNotReadableException exception, HttpServletResponse response){
LOGGER.error("请求参数不匹配。", exception);
return CodeMsg.error(exception.getMessage());
}
{
"code": 1,
"msg": "Could not read JSON: Failed to parse Date value '2017-03-' (format: \"yyyy-MM-dd HH:mm:ss\"): Unparseable date: \"2017-03-\" (through reference chain: com.test.modules.order.entity.Order[\"serveTime\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to parse Date value '2017-03-' (format: \"yyyy-MM-dd HH:mm:ss\"): Unparseable date: \"2017-03-\" (through reference chain: com.test.modules.order.entity.Order[\"serveTime\"])",
"data": ""
}
Indicates the annotated class assists a "Controller".
Serves as a specialization of {@link Component @Component}, allowing for implementation classes to be autodetected through classpath scanning.
It is typically used to define {@link ExceptionHandler @ExceptionHandler},
* {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute}
* methods that apply to all {@link RequestMapping @RequestMapping} methods.
One of {@link #annotations()}, {@link #basePackageClasses()},
* {@link #basePackages()} or its alias {@link #value()}
* may be specified to define specific subsets of Controllers
* to assist. When multiple selectors are applied, OR logic is applied -
* meaning selected Controllers should match at least one selector.
the default behavior (i.e. if used without any selector),
* the {@code @ControllerAdvice} annotated class will
* assist all known Controllers.
Note that those checks are done at runtime, so adding many attributes and using * multiple strategies may have negative impacts (complexity, performance).
@ResponseBody
@ControllerAdvice("com.api")
public class ApiExceptionHandler extends BaseClientController {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class);
/**
*
* @param exception UnexpectedTypeException
* @param response
* @return
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(UnexpectedTypeException.class)
public CodeMsg unexpectedType(UnexpectedTypeException exception, HttpServletResponse response){
LOGGER.error("校验方法太多,不确定合适的校验方法。", exception);
return CodeMsg.error(exception.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public CodeMsg messageNotReadable(HttpMessageNotReadableException exception, HttpServletResponse response){
LOGGER.error("请求参数不匹配,request的json格式不正确", exception);
return CodeMsg.error(exception.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
public CodeMsg ex(MethodArgumentNotValidException exception, HttpServletResponse response){
LOGGER.error("请求参数不合法。", exception);
BindingResult bindingResult = exception.getBindingResult();
String msg = "校验失败";
return new CodeMsg(CodeMsgConstant.error, msg, getErrors(bindingResult));
}
private Map<String, String> getErrors(BindingResult result) {
Map<String, String> map = new HashMap<>();
List<FieldError> list = result.getFieldErrors();
for (FieldError error : list) {
map.put(error.getField(), error.getDefaultMessage());
}
return map;
}
}
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.0.2.Final</version> </dependency>
<mvc:annotation-driven validator="validator" /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <property name="validationMessageSource" ref="messageSource"/> </bean>
public class AlipayRequest {
@NotEmpty
private String out_trade_no;
private String subject;
@DecimalMin(value = "0.01", message = "费用最少不能小于0.01")
@DecimalMax(value = "100000000.00", message = "费用最大不能超过100000000")
private String total_fee;
/**
* 订单类型
*/
@NotEmpty(message = "订单类型不能为空")
private String business_type;
//....
}
@RequestMapping(value = "sign", method = RequestMethod.POST)
public String sign(@Valid @RequestBody AlipayRequest params
){
....
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
public CodeMsg ex(MethodArgumentNotValidException exception, HttpServletResponse response){
LOGGER.error("请求参数不合法。", exception);
BindingResult bindingResult = exception.getBindingResult();
String msg = "校验失败";
return new CodeMsg(CodeMsgConstant.error, msg, getErrors(bindingResult));
}
private Map<String, String> getErrors(BindingResult result) {
Map<String, String> map = new HashMap<>();
List<FieldError> list = result.getFieldErrors();
for (FieldError error : list) {
map.put(error.getField(), error.getDefaultMessage());
}
return map;
}
{
"code": 1,
"msg": "校验失败",
"data": {
"out_trade_no": "不能为空",
"business_type": "订单类型不能为空"
}
}
/** * Bean Validation 中内置的 constraint * @Null 被注释的元素必须为 null * @NotNull 被注释的元素必须不为 null * @AssertTrue 被注释的元素必须为 true * @AssertFalse 被注释的元素必须为 false + * @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 * @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 * @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 * @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 * @Size(max=, min=) 被注释的元素的大小必须在指定的范围内 * @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内 * @Past 被注释的元素必须是一个过去的日期 * @Future 被注释的元素必须是一个将来的日期 * @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式 * Hibernate Validator 附加的 constraint * @NotBlank(message =) 验证字符串非null,且长度必须大于0 * @Email 被注释的元素必须是电子邮箱地址 * @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内 * @NotEmpty 被注释的字符串的必须非空 * @Range(min=,max=,message=) 被注释的元素必须在合适的范围内 */
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有