• 请不要在回答技术问题时复制粘贴 AI 生成的内容
sandman511
V2EX  ›  程序员

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

  •  
  •   sandman511 · Dec 17, 2019 · 2352 views
    This topic created in 2517 days ago, the information mentioned may be changed or developed.

    正确输入应该是 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 replies  •  2019-12-18 14:10:32 +08:00
    CStarter
    CStarter
    Dec 17, 2019 via Android
    1
    正则比 exception 好
    speedofstephen
    speedofstephen
    Dec 17, 2019
    2
    ??你用的什么框架。如果是 spring 为什么不直接用 Integer 呢?
    linauror
    linauror
    Dec 17, 2019
    3
    错误码+错误消息
    gotonull
    gotonull
    Dec 17, 2019
    4
    定义一个全局异常处理啊
    securityCoding
    securityCoding
    Dec 17, 2019
    5
    tubimasky
    tubimasky
    Dec 17, 2019 via Android
    6
    hirenate 验证包?
    crella
    crella
    Dec 17, 2019 via Android
    7
    html 路径的参数不都是 string 的吗?

    如果 java 里面不是这样,先把所有参数都转为 string,然后尝试转 integer,如果转换结果为 0 或者抛出异常就判断是错误参数。
    superrichman
    superrichman
    Dec 17, 2019
    8
    这种就应该不做任何提示给前端. 等你以后吃过亏了就会懂.
    sandman511
    sandman511
    OP
    Dec 18, 2019
    9
    @Tranvin 好的 我把异常处理改成正则
    sandman511
    sandman511
    OP
    Dec 18, 2019
    10
    @speedofstephen springboot 改成 Integer 的话,如果用户输入字母,直接报错了 400 了。无法返回 json
    sandman511
    sandman511
    OP
    Dec 18, 2019
    11
    @superrichman 请问这是为什么呢?直接给前端 400 吗
    sandman511
    sandman511
    OP
    Dec 18, 2019
    12
    @xzceprint 百度了一下,这好像确实是我想要的解决方法 谢谢!
    speedofstephen
    speedofstephen
    Dec 18, 2019
    13
    @sandman511 对阿,400 不就是外部错误么。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1090 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 17:12 · PVG 01:12 · LAX 09:12 · JFK 12:12
    ♥ Do have faith in what you're doing.