Pre-js basics

try catch

This is a common error handler

try { const a = {}; a(); } catch(err) {console.log('try logic error '); }Copy the code

If a block of code fails in a try, it goes to catch logic. And within that block, the logic in the catch will be printed out.

But let’s put it another way

try { setTimeout(() => { const a = {}; a(); })} catch(err) {console.log('try logic error '); }Copy the code

This is the asynchronous case that we see all the time. In this case, the catch cannot catch the error in the try.

To sum up, catch can only catch synchronous errors, and cannot do anything about asynchronous errors.

Note: if there is a finally case, then either the try logic or the catch logic will go to finally logic. In an extreme case, if you return ina try and also return ina catch, finally will automatically ignore its return and use its own return value

function test() { try { return 1; } catch { return 2; } finally { return 3; } } test(); / / 3Copy the code

Browser monitoring error

Window. onError, or addEventListener for error events, is the type of monitoring we use to listen for errors at the Window level. When an error is not caught or handled correctly, an error is thrown, stopping the current macro task.

However, when the Promise reject behavior is not handled, an error is also thrown in the console, and instead of listening for the error event, it listens for the RejectionHandled event

Node layer monitoring error

Therefore, when catching node errors, we can think of js catching errors

  1. try catchDafa, in the case of synchronization errors,try catchThe land use
  2. process.on('uncaughtException')If an error is not caught in the code logic, it will end up here, which could look like the windowerrorEvent, in which case node services are unavailable.
  3. process.on('unhandledRejection')This is used when a Reject action is left unprocessed in a Promise

Therefore, when we need to do error monitoring, we generally monitor uncaughtException. At the same time, if we are aware of the try catch logic processing, in order to maintain the stability of the application, we should do the try catch application logic and report it in the catch. However, after the Promise is rejected, there is no corresponding processing function, and it should also be reported.

This is the logic that should be used for error monitoring, but at the same time, we should also consider various error handling situations in our code, to avoid the end of the uncaught error (uncaughtException).

About the realization of the asynchronous error trapping, in the node zhuanlan.zhihu.com/p/62210238 can see this article

Monitoring with nestJS framework

Nestjs framework will have its own exception handling logic, we can increase the global HTTP request filter by adding interceptors, convert asynchronous requests to async await writing, and use try catch to wrap the logic in it, so as to achieve interception effect. Specific as follows:

// exception-interception.ts @Injectable() export class ErrorsInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next .handle() .pipe( catchError((err) => { const request = context.switchToHttp().getRequest(); console.error(err, '=======err'); reportError({ log: err.stack, req: request }); Return throwError(new HttpException(' error ', 500))}),); } } // app.controller.ts @UseInterceptors(new ErrorsInterceptor()) @Controller('**') export class AppController {}Copy the code

You can monitor services and monitor uncaughtException and unhandleRejection to report errors

process.on('unhandledRejection', err => { console.log('err', err, 'unhandledRejection'); reportError(err); On ('uncaughtException', err => {console.error(' there is an uncaught error ', err); reportError(err); Process.exit (1) // Mandatory (according to node.js documentation)});Copy the code

Error handling

Therefore, in our own business logic, in order to avoid the last irreversible situation, we should try our best to pay attention to the business and deal with it.

  1. Determine the type and return value, and pay attention to error handling during I/O operations

  2. Any use of JavaScript’s throw mechanism raises an exception, which must use a try… Otherwise, the Node.js process will exit immediately.

  3. Handle the Promise reject behavior correctly