Spring Boot句柄类型不匹配错误 [英] Spring boot handle type mismatch errors

查看:95
本文介绍了Spring Boot句柄类型不匹配错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Boot 2.1.5,并且有一个类映射到从表单提交的数据.该类具有一个整数字段:

I'm using Spring Boot 2.1.5, and I have a class that is mapped to data submitted from a form. The class has an integer field:

class FormData {
   private Integer id;
   ...
}

当我发送错误类型的有效载荷时,例如:

When I send a payload with the wrong type, e.g:

{
  id: "aaaa"
}

Spring静默返回400状态,不引发任何异常,并且没有任何内容输出到控制台.我想在发生这种情况时以某种方式捕获此错误,以便能够返回适当的自定义错误.我基本上将bean验证用于所有其他验证,但是我找不到一种将其应用于类型不匹配的方法.

Spring silently returns a 400 status, no exception is thrown, and nothing is printed to the console. I would like to somehow catch this when this happens, so that I would be able to return a proper custom error. I basically use bean validation for all of my other validations, but I can't find a way to apply it for a type mismatch.

谢谢.

推荐答案

此无效的参数类型转换将引发

This invalid parameter type conversion throws a TypeMismatchException, that you can handle with a method annotated with @ExceptionHandler, for example, like this :

@ExceptionHandler(TypeMismatchException.class)
@ResponseBody
public MyErrorResponse handleTypeMismatchException(TypeMismatchException typeMismatchException) {
    // create my error response
}

您可以将此方法放置在一个控制器内(在这种情况下,它将仅处理该控制器抛出的异常),或放置在以

You can place this method inside one controller (in which case it's going to handle only exceptions thrown by this controller), or inside a class annotated with @ControllerAdvice (so it will be generalized to all your controllers).

这篇关于Spring Boot句柄类型不匹配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆