在实际业务中,有时候需要前后的统一维护异常,如某输入框,只能输入文字,除了前端需要控制,后端也需要控制,如果前端某些地方没有把控好,这个请求就到后端了,可能会抛出转换异常,非常的不优雅,今天分享一下后端把控的方法,如有帮助,请大佬点个赞,或者收藏。
1,创建一个Error.properties,名字根据自己业务命名
2,创建一个异常处理类
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice @ResponseBody //下面这个注解是指定读取哪个配置文件的,不能省 啊,不然读取不到配置文件,路径根据实际文件存放的位置写。 @PropertySource(value = "classpath:Error.properties") public class ExceptionHandler { //将配置文件最为一个对象注入进来 @Autowired