V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
sandman511
V2EX  ›  程序员

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

  •  
  •   sandman511 · 2019-12-17 14:25:18 +08:00 · 1629 次点击
    这是一个创建于 1564 天前的主题,其中的信息可能已经有所发展或是发生改变。

    正确输入应该是 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("参数错误");
        }
    
    13 条回复    2019-12-18 14:10:32 +08:00
    CStarter
        1
    CStarter  
       2019-12-17 15:12:00 +08:00 via Android
    正则比 exception 好
    speedofstephen
        2
    speedofstephen  
       2019-12-17 16:58:20 +08:00
    ??你用的什么框架。如果是 spring 为什么不直接用 Integer 呢?
    linauror
        3
    linauror  
       2019-12-17 17:14:24 +08:00
    错误码+错误消息
    gotonull
        4
    gotonull  
       2019-12-17 17:54:52 +08:00
    定义一个全局异常处理啊
    securityCoding
        5
    securityCoding  
       2019-12-17 17:56:38 +08:00
    tubimasky
        6
    tubimasky  
       2019-12-17 18:10:10 +08:00 via Android
    hirenate 验证包?
    crella
        7
    crella  
       2019-12-17 18:17:50 +08:00 via Android
    html 路径的参数不都是 string 的吗?

    如果 java 里面不是这样,先把所有参数都转为 string,然后尝试转 integer,如果转换结果为 0 或者抛出异常就判断是错误参数。
    superrichman
        8
    superrichman  
       2019-12-17 18:49:57 +08:00
    这种就应该不做任何提示给前端. 等你以后吃过亏了就会懂.
    sandman511
        9
    sandman511  
    OP
       2019-12-18 10:02:25 +08:00
    @Tranvin 好的 我把异常处理改成正则
    sandman511
        10
    sandman511  
    OP
       2019-12-18 10:03:22 +08:00
    @speedofstephen springboot 改成 Integer 的话,如果用户输入字母,直接报错了 400 了。无法返回 json
    sandman511
        11
    sandman511  
    OP
       2019-12-18 10:04:36 +08:00
    @superrichman 请问这是为什么呢?直接给前端 400 吗
    sandman511
        12
    sandman511  
    OP
       2019-12-18 10:19:37 +08:00
    @xzceprint 百度了一下,这好像确实是我想要的解决方法 谢谢!
    speedofstephen
        13
    speedofstephen  
       2019-12-18 14:10:32 +08:00
    @sandman511 对阿,400 不就是外部错误么。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5404 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 07:06 · PVG 15:06 · LAX 00:06 · JFK 03:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.