[英]I want to throw custom Error with status code using Throw function in response body
If I use Throw new Error("User not found"), then it gives in response如果我使用 Throw new Error("User not found"),那么它会给出响应
{status:false,message:"User Not Found"}
But with status code 500, And I need Status 400 in Postman但是状态码为 500,我需要 Postman 中的状态码 400
custom Error using throw function自定义错误使用 throw function
but if we use res.status(500).send({ status: false, message: "User not found" })
但是如果我们使用
res.status(500).send({ status: false, message: "User not found" })
then it gives status code 400, And I need Status 400 in Postman. So, I need same status code in postman only.This is the problem.然后它给出状态代码 400,我需要 Postman 中的状态 400。因此,我只需要 postman 中的相同状态代码。这就是问题所在。 Tyler2P and Abin Bala, I followed your code but I am unable to get desired status code in postman status.
Tyler2P 和 Abin Bala,我遵循了你的代码,但我无法在 postman 状态中获得所需的状态代码。
You can create a custom error class as below and throw it with appropriate message and httpCode.您可以创建一个自定义错误 class,如下所示,并使用适当的消息和 httpCode 将其抛出。 You can also add more properties.
您还可以添加更多属性。 Then you can catch the custom error object using the catch block and get the required values.
然后您可以使用 catch 块捕获自定义错误 object 并获取所需的值。
class CustomError extends Error {
name;
httpCode;
message;
constructor(name,httpCode, message){
super(message);
this.name = name;
this.httpCode = httpCode;
this.message = message;
}
}
errorThrowingFunction.js
: errorThrowingFunction.js
:
//import the custom error class in the module that you //are going to use it.
errorThrowingFunction = () => {
const authToken = myCache.get("token");
if (!authToken) {
throw new CustomError('Error',401,'token missing');
} else {
return authToken;
}
}
index.js
: index.js
:
handler = () => {
try {
errorThrowingFunction();
} catch(error){
const response = {
statusCode: error.httpCode,
body: JSON.Stringify(error.message),
isBase64Encoded: false,
//add other headers
}
return response;
//if you are using this in rest service, the use below line
//return res.status(error.httpCode)send(response);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.