#samuelDSR-nodejs-error
1 messages ยท Page 1 of 1 (latest)
const {
Stripe: { StripeError },
} = require("stripe");
const buildErrorSchema = (code, type, message) => {
return { code, type, message };
};
/**
*
* @param {Error} err
* @param {import("express").Request} _req
* @param {import("express").Response} res
* @param {import("express").NextFunction} _next
*/
const errorHandler = (err, _req, res, _next) => {
console.error({ err, r: err?.response });
// Custom error response
if (err instanceof CustomError) {
return res.status(err.errorCode).json(err.serializeError());
}
// Malformed json
if (err instanceof SyntaxError) {
return res
.status(400)
.json(buildErrorSchema(400, "BAD_REQUEST", err.message));
}
// Stripe error
if (err instanceof StripeError) {
// do something
}
if (err.response) {
// Error calling a third party service
const { data } = err.response;
let message = null;
if (data.message) {
message = data.message;
} else if (data.error_message) {
// Specific from plaid error response
message = data.error_message;
}
return res.status(400).json(buildErrorSchema(400, "BAD_REQUEST", message));
} else {
// Unexpected errors
return res
.status(500)
.json(
buildErrorSchema(
500,
"SERVER_ERROR",
process.env.NODE_ENV !== "production"
? err.message
: "An unexpected error occurred."
)
);
}
};
module.exports = errorHandler;
I'm not sure if I'm importing the error class correctly, in the docs the error parsing they say is with a switch & based on err.type, but I prefer this instanceof way cuz I'm using other third party services
sorry for my english btw ๐
Have you checked for circular dependencies? Does ../errors depend on anything in the code from this file?
Nope, it only contains class definitions for my custom errors
Hmmm, I'm not sure what else to have you try here. Let me see if anyone else on my team has an idea
Do you know which line specifically is creating the error?
I'm creating the error on purpose, just want to parse it correctly in the middleware
Okay, so you're expecting there not to be an object for the right side of the instanceof condition? In other words, you want this error to occur: TypeError: Right-hand side of 'instanceof' is not an object?
No, I would like to return a custom response to the user when my app launch an error caused by stripe, so I need a way to check if the exception is from stripe, and I'm currently gettin that TypeError
I suspect that stripe library has a class hierarchy to represent his custom Error responses, and I think it base Error class is StripeError, so i'm using it
Right, that makes sense. Let me dig a bit more and get back to you
Still digging here. Brb
From the Errors.d.ts in Stripe.types there's this comment
/**
* @deprecated The {@link Stripe.StripeError} type is deprecated, please use {@link Stripe.errors.StripeError}.
*/
It might be as simple as importing Stripe.errors.StripeError instead of Stripe.StripeError?
Amazing! Glad that worked, because it would've been a real head-scratcher if it didn't