编写接口。用户输入参数错误,如何返回消息提醒用户

2019-12-17 14:25:18 +08:00
 sandman511

正确输入应该是 http://localhost:8080/test?id=7777777 结果用户输入了 http://localhost:8080/test?id=bye

我该如何返回 json 中带 msg 告知用户输入参数错误 而不是返回 400

目前想法是接受 id 为 String,不过这也太蠢了,请问有其他方法吗?谢谢

    try{
        Integer idd = Integer.valueOf(id);
    }catch(Exception e){
        return Result.validationError("参数错误");
    }
1643 次点击
所在节点    程序员
13 条回复
CStarter
2019-12-17 15:12:00 +08:00
正则比 exception 好
speedofstephen
2019-12-17 16:58:20 +08:00
??你用的什么框架。如果是 spring 为什么不直接用 Integer 呢?
linauror
2019-12-17 17:14:24 +08:00
错误码+错误消息
gotonull
2019-12-17 17:54:52 +08:00
定义一个全局异常处理啊
securityCoding
2019-12-17 17:56:38 +08:00
tubimasky
2019-12-17 18:10:10 +08:00
hirenate 验证包?
crella
2019-12-17 18:17:50 +08:00
html 路径的参数不都是 string 的吗?

如果 java 里面不是这样,先把所有参数都转为 string,然后尝试转 integer,如果转换结果为 0 或者抛出异常就判断是错误参数。
superrichman
2019-12-17 18:49:57 +08:00
这种就应该不做任何提示给前端. 等你以后吃过亏了就会懂.
sandman511
2019-12-18 10:02:25 +08:00
@Tranvin 好的 我把异常处理改成正则
sandman511
2019-12-18 10:03:22 +08:00
@speedofstephen springboot 改成 Integer 的话,如果用户输入字母,直接报错了 400 了。无法返回 json
sandman511
2019-12-18 10:04:36 +08:00
@superrichman 请问这是为什么呢?直接给前端 400 吗
sandman511
2019-12-18 10:19:37 +08:00
@xzceprint 百度了一下,这好像确实是我想要的解决方法 谢谢!
speedofstephen
2019-12-18 14:10:32 +08:00
@sandman511 对阿,400 不就是外部错误么。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/629813

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX