question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Docs: improve sample code for global catch all exceptions

See original GitHub issue

I’m submitting a…


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request (new chapter/page)
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Exceptions chapter, possible example code improvement.

Expected behavior

If you were to implement the “Catch Everything” code sample in the Exception filters chapter, it would work as described.

Minimal reproduction of the problem with instructions

Simply implement this http-exception filter (with empty @Catch() decorator) to handle all exceptions as shown in the docs. Then issue a throw new Error('boom'); in the CatsController to simulate a non-HTTP exception arising, and make the http request.

What is the motivation / use case for changing the behavior?

The problem is that the code sample includes the code: const status = exception.getStatus(); but a vanilla Error class doesn’t have this method.

I would propose something like the following. If acceptable, I’ll include it in an upcoming PR for this chapter.

import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    // default HTTP response code for non HttpException errors is
    // 500 - Internal Server Error
    let status = 500;
    if (exception instanceof HttpException) {
      status = exception.getStatus();
    }

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}

Environment


For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
kamilmysliwieccommented, Apr 10, 2019

Good point @lazarljubenovic. Also, we could define 500 value as a constant variable (or use HttpStatus enum) instead of adding a comment.

const status = exception instanceof HttpException
  ? exception.getStatus()
  : HttpStatus.INTERNAL_SERVER_EROR;

It’s ^ self-descriptive I think.

2reactions
lazarljubenoviccommented, Apr 10, 2019

It might be clearer to write

const status = exception instanceof HttpException
  ? exception.getStatus()
  : 500

instead of overwriting status, since it’s only a single condition.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Catch All Exceptions in C# & Find All Application Errors
Catch all exceptions in your application with a C# global exception handler and other exception handling methods.
Read more >
Best Practices for exceptions - .NET - Microsoft Learn
Learn best practices for exceptions, such as using try/catch/finally, handling common conditions without exceptions, and using predefined .
Read more >
Complete Guide to Exception Handling in Spring Boot
This article showcases various ways to handle exceptions in a Spring Boot Application.
Read more >
How can I write a `try`/`except` block that catches all exceptions?
If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action...
Read more >
How to Handle Exceptions in JavaScript - Rollbar
In most instances, however, catching every exception thrown is considered bad practice. It is far more manageable to specifically catch and ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found