简体   繁体   English

优雅的 JSON.parse 异常处理程序

[英]Elegant JSON.parse exception handler

Say we have a function that calls JSON.parse(someText) multiple times.假设我们有一个函数多次调用JSON.parse(someText) However, someText is not necessarily error checked, for ex, "foo" could be passed into JSON.parse.但是, someText不一定会进行错误检查,例如,可以将"foo"传递到 JSON.parse。 When a non JSON value is inputted, I want to return an empty object, {}当输入非 JSON 值时,我想返回一个空对象, {}

Obviously, we can use a try-catch to easily handle this.显然,我们可以使用try-catch来轻松处理这个问题。 However, try-catch is ugly and not elegant - is there a quick, simple, one liner way to do something like this?然而, try-catch既丑陋又不优雅——有没有一种快速、简单、单行的方式来做这样的事情?

(this goes to future readers that don't get why this is wrong) You are supposed to catch and handle exceptions, not ignore them. (这适用于不明白为什么这是错误的未来读者)您应该捕获和处理异常,而不是忽略它们。 People that develop these functions rely on you catching exceptions to be able to properly react to them breaking.开发这些功能的人依赖于您捕获异常,以便能够对它们的中断做出正确的反应。 Elegance and beauty are in the eyes of the beholder, and as with any piece of art, you write it so that other people will enjoy it.优雅和美丽在旁观者的眼中,就像任何艺术品一样,你写它是为了让其他人喜欢它。 And everyone gets try...catch blocks.每个人都会得到try...catch块。

There's no way to do it in 1 line of code.没有办法在 1 行代码中做到这一点。 You can however, do some nasty stuff to bypass exception handling.但是,您可以做一些讨厌的事情来绕过异常处理。


METHOD 1方法一

Manually handle the global onError method.手动处理全局 onError 方法。

function handleErr(msg, url, line_no){ 
   var errorMsg = "Error: " + msg + "\n"; 
       errorMsg += "URL: " + url + "\n"; 
       errorMsg += "Line: " + line_no + "\n\n"; 

    console.log(errorMsg); 

 return true;
} 

// Set the global onerror; 
onerror = handleErr;

Now you handle (ie ignore) errors in this function.现在您处理(即忽略)此函数中的错误。 You can switch it on and off with a bit code.您可以使用位代码打开和关闭它。 Or you can go bananas and just do a return true;或者你可以去香蕉,只是做一个return true; in the handler.在处理程序中。


METHOD 2方法二

Use setTimeout, the thread will die due to the exception but your code will keep executing, also a beautiful ES6 one-liner.使用 setTimeout,线程会因为异常而死亡,但你的代码会继续执行,也是一个漂亮的 ES6 单线。

setTimeout(() => JSON.parse("not json: fghfghg"), 0)
console.log("Code still running")

METHOD 3方法三

For non-mainstream, "Elegant" exception handling you can implement and use Either ( example )对于非主流的“优雅”异常处理,您可以实现和使用任一示例

Despite previous comments about exception handling, you can apply a one-liner to achieve your goal.尽管之前有关于异常处理的评论,但您可以应用单行代码来实现您的目标。 The only catch is numbers and numeric strings;唯一的问题是数字和数字字符串; those will be parsed and returned as numbers这些将被解析并作为数字返回

 let input = 'someText' let parsedText = (() => { try { return JSON.parse(input) } catch { return {} }}).call() console.info(parsedText) // {} input = '{ "hello": "world" }' parsedText = (() => { try { return JSON.parse(input) } catch { return {} }}).call() console.info(parsedText) // { hello: 'world' } input = '9' parsedText = (() => { try { return JSON.parse(input) } catch { return {} }}).call() console.info(parsedText) // 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM