javascript 如何使用状态代码抛出异常?

jfgube3f  于 2022-10-30  发布在  Java
关注(0)|答案(5)|浏览(132)

如何使用选项或状态码掷回错误,然后加以拦截?
从语法here看来,我们似乎可以通过错误附带附加信息:

new Error(message, options)

我们能像这样扔下去吗?

throw new Error('New error message', { statusCode: 404 })

那么,我们怎么才能抓住那个statusCode呢?

try {
 //...
} catch (e) {
  console.log(e.statusCode) // not working off course!
}

有什么想法吗?
选项是not supported尚未。
重新抛出错误工作方式:

try {
  const found = ...

  // Throw a 404 error if the page is not found.
  if (found === undefined) {
    throw new Error('Page not found')
  }

} catch (error) {
  // Re-throw the error with a status code.
  error.statusCode = 404
  throw error
}

但这并不是一个完美的解决方案。

8ljdwjyq

8ljdwjyq1#

您可以使用错误代码

const error = new Error("message")
error.code = "YOUR_STATUS_CODE"
throw error;
wgeznvg7

wgeznvg72#

如此处所述,您必须为此创建自定义例外:

function CustomException(message) {
  const error = new Error(message);

  error.code = "THIS_IS_A_CUSTOM_ERROR_CODE";
  return error;
}

CustomException.prototype = Object.create(Error.prototype);

然后可以抛出自定义异常:

throw new CustomException('Exception message');
j5fpnvbx

j5fpnvbx3#

基于响应

const error = new Error(response?.error || 'error message here'); // error message
error.code = response?.code || 404; // you can custom insert your error code
error.name = "NOT FOUND"; // you can custom insert your error name
throw error;
jslywgbw

jslywgbw4#

我也有类似的需求,并创建了自己的Error类来提供所需的功能:

interface ApiErrorOptions extends ErrorOptions {
  status?: number;
}

class ApiError extends Error {
  status: number;
  constructor(message: string, options?: ApiErrorOptions) {
    super(message, { cause: options?.cause });
    this.status = options?.status;
  }
}

export async function getApiError(response: Response) {
  const body = await response.json();
  return new ApiError(body.msg || "server_error", {
    status: body?.status,
  });
}
ukxgm1gy

ukxgm1gy5#

try{
 // custom error throw in javascript ...   

 const exception = new Error();
 exception.name = "CustomError";

  exception.response = {
    status: 401,
    data: {
      detail: "This is a custom error",
    },
 };

 throw exception;

} catch (err) {
 //console error with status...
  console.log(err.response);
}

相关问题