Don’t use try catch in JavaScript

0 views

Published on

April 5, 2016. 東京node学園 #20 ( http://nodejs.connpass.com/event/29235/ )

Published in: Engineering
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
0
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Don’t use try catch in JavaScript

  1. 1. DON’T USE TRY-CATCH Tetsuharu OHZEKI aka @saneyuki_s April 5, 2016. 東京node学園 #20
  2. 2. ABOUT ME • Tetsuharu OHZEKI • twitter: saneyuki_s • Open Source Contributor • Mozilla Committer • Firefox, Servo (as reviewer) • ReactiveX/RxJS • And some others… • whatwg html, etc • Working atVOYAGE GROUP, inc. • My main work is to develop an advertising management system with using TypeScript, babel compiler, React, and RxJS.
  3. 3. DO YOU USE TRY-CATCH?
  4. 4. DO YOU THROW AN ERROR?
  5. 5. TWO TYPES OF “ERROR” •Just a Bug • NullPointerException,TypeError, calling undefined methods, not found a required file, etc... •Recoverable Errors • Network timeout, JSON parse errors, etc…
  6. 6. CAN YOU RECOVER A BUG IN A RUNNING APPLICATION? No • A bug is just a programming mistake. • Don’t recover them. • So “let it crash”,“abandonment”,“fail-fast” immediately. • Even if you success recovering from their fatal, there’re some serious conformity problem in your heap.
  7. 7. Promise/Observable.catch() are any type in TypeScript definitions. This is a hole for type restriction. interface Promise<T> { catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>; catch(onrejected?: (reason: any) => void): Promise<T>; } interface Observable<T> { catch<R>(selector: (err: any, caught: Observable<T>) => Observable<R>): Observable<R>; }
  8. 8. CAN WE USE TRY-CATCH FOR RECOVERABLE? • I don’t think so excluding some exceptions… • (of course, we have to handle errors from builtin object, dom, libraries, ete with try-catch) • “error throw-ablity” should be restricted by a function signature. • should force an error handling for a caller!
  9. 9. function parseJSON(obj) { try { const value = JSON.parse(obj); return value; } catch (e) { return null; } }
  10. 10. HOW DO WE REPRESENT “ERROR THROWABLE” TYPE?
  11. 11. RETURN A “RESULT TYPE” THAT IS LIKE A ITERATOR’S RESULT. interface ErrorContainableResult<T, E> { ok: boolean; value:T; error: E; }
  12. 12. const { ok, value, error } = doSome(); if (ok) { // handle value } else { // handle error }
  13. 13. doSomePromise().then((result) => { const { ok, value, error } = result; if (ok) { // handle value } else { // handle error } }, (unrecover) => crash(unrecover)).;
  14. 14. doSomeRxObservable().subscribe((result) => { const { ok, value, error, } = result; // blah, blah, blah }, (unrecover) => crash(unrecover));
  15. 15. process.on(‘uncaughtException’, (reason) => { // dump error report process.exit(); }); throw new Error(‘Hello! This is fatal bug’);
  16. 16. INTRODUCE RESULT<T, E>
  17. 17. RESULT<T, E> • Result<T, E> == Either<A, B> • You can use it from npm:option-t • APIs are inspired by Rustlang’s std::result • There are some instance methods • This provides “utility” object & methods. • You can same things with destructuring assignment.
  18. 18. const result = getSomeResult(); if ( result.isOk() ) { // success } else { // error }
  19. 19. const result = getSomeResult(); const value: string = result .map((v: number) => String(v)).unwrap(); const first = getSomeResult(); const second = first.andThen(first => { return getSecondResult(first); });
  20. 20. type Result<T,E> = Ok<T, E> | Err<T, E>; class Ok<T, E> implements ResultMethods<T,E>; class Err<T, E> implements ResultMethods<T,E>; interface ResultMethods<T,E> { ok(): Option<T>; err(): Option<E>; isOk(): boolean; isErr(): boolean; map<U>(op: MapFn<T,U>): Result<U,E>; mapErr<F>(op: MapFn<E,F>): Result<T,F>; andThen<U>(op: FlatmapOkFn<T,U, E>): Result<U,E>; orElse<F>(op: FlatmapErrFn<T, E, F>): Result<T,F>; unwrap():T; unwrapErr(): E; }
  21. 21. SEE HTTPS://DOC.RUST-LANG.ORG/BOOK/ERROR- HANDLING.HTML
  22. 22. DRAWBACKS IN JAVASCRIPT • Need a extra object allocation cost • In the future, JavaScript runtime may make the cost more cheap. • Don’t use them if you require computation performance extremely. • Result<T, E> type needs static type analytics for more convenient/secure programming (but plain JavaScript is not so). • Let’s use withTypeScript or Flowtype 
  23. 23. •DO NOT TRY TO RECOVER A BUG • Don’t suppress a bug. FIX it. •Don’t use try-catch • Excluding: Runtime provided functions (include JSON.parse, DOM),ssand 3rd party libraries. •Tell “Error-Throwable” via function signature.

×