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.

question: How do I customize internal HttpErrors with custom Http errors with KoaDriver?

See original GitHub issue

I was sending custom HttpErrors that changes the response to the user but I can’t do this when I’m validating request bodies because it’s using the one that came with the library.

This is the response I want to throw when a validation fails;

{
    "status": false,
    "message": "Validation errors.",
    "errors": "ValidationError[] from class validator"
}

This is what it currently returns

{
    "name": "BadRequestError",
    "message": "Invalid body, check 'errors' property for more info.",
     "errors": "ValidationError[] from class validator"
}

One way that I could find is to use this but since I’m using Koa I can’t use it.

One workaround for this is disabling the validator from @Body() and calling class-validator inside the request function.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:5
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
kasir-baraticommented, Aug 28, 2021

If I remember correctly you can use custom error handlers with express.

Here’s the doc for the interface.

Hi, I solve it. IDK why, but the ValidationError was in the error.errors and it was an array of ValidationError. so i did this kind of trick to send the error message to the client:

class CustomValidationError {
    errors: ValidationError[];
}

/* CustomErrorHandler class - error method */
if (
    'errors' in error &&
    error.errors[0] instanceof ValidationError
) {
    const errorMessages: { [x: string]: string }[] = findProp(
        error,
        'constraints',
    );

    response
        .status(400)
        .json(new ErrorResponse(false, getValues(errorMessages)));
}

function findProp(obj: any, key: string, result: any[] = []): any[] {
    const proto = Object.prototype;
    const ts = proto.toString;
    const hasOwn = proto.hasOwnProperty.bind(obj);

    if ('[object Array]' !== ts.call(result)) {
        result = [];
    }

    for (let i in obj) {
        if (hasOwn(i)) {
            if (i === key) {
                result.push(obj[i]);
            } else if (
                '[object Array]' === ts.call(obj[i]) ||
                '[object Object]' === ts.call(obj[i])
            ) {
                findProp(obj[i], key, result);
            }
        }
    }

    return result;
}

function getValues(arrayOfObjects: { [x: string]: string }[]): string[] {
    const result: string[] = [];

    for (let item of arrayOfObjects) {
        result.push(...Object.values(item));
    }

    return result;
}

and with this trick, I resolve it. HOPE this would be helpful later. 🎯

0reactions
attilaoroszcommented, Dec 21, 2022

Closing this as stale.

If the issue still persists, you may open a new Q&A in the discussions tab and someone from the community may be able to help.

Read more comments on GitHub >

github_iconTop Results From Across the Web

HTTP Errors <httpErrors> - Microsoft Learn
In the Add Custom Error Page dialog box, under Status code, type the number of the HTTP status code for which you want...
Read more >
How do I display custom error pages in Asp.Net Mvc 3?
I have tried using a combination <custom errors> and <httpErrors> with no luck - the standard error or blank page is still displayed....
Read more >
How To Implement Custom Error Responses in Express - Auth0
Therefore, you need to customize error responses to provide the client with more details about the problem that occurred.
Read more >
Custom error pages - Sitefinity CMS Setup and maintenance
Navigate to Administration » Settings » Advanced » Pages » Custom error pages » Error types » Create new. In HTTP status code,...
Read more >
Custom errors, extending Error - The Modern JavaScript Tutorial
When we develop something, we often need our own error classes to reflect specific things that may go wrong in our tasks.
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