Как правильно обработать ошибки с помощью TypeScript? [закрыто]Javascript

Форум по Javascript
Ответить
Anonymous
 Как правильно обработать ошибки с помощью TypeScript? [закрыто]

Сообщение Anonymous »

Мы следуем этой документации о том, как обрабатывать ошибки, выброшенные Docxtemplater. Мы не хотели бы использовать какой -либо в качестве типа, если это необходимо.function replaceErrors(key, value) {
if (value instanceof Error) {
return Object.getOwnPropertyNames(value).reduce(
function (error, key) {
error[key] = value[key];
return error;
},
{}
);
}
return value;
}

try {
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
doc.render();
} catch (error) {
// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
console.log(JSON.stringify({ error }, replaceErrors));

if (
error.properties &&
error.properties.errors instanceof Array
) {
const errorMessages = error.properties.errors
.map(function (error) {
return error.properties.explanation;
})
.join("\n");
console.log("errorMessages", errorMessages);
/*
* errorMessages is a humanly readable message looking like this:
* 'The tag beginning with "foobar" is unopened'
*/
}
throw error;
}

Использование ошибки как тип не работает в двух случаях, см. Комментарии ниже:
function replaceErrors(key: string, value: Error) {
if (value instanceof Error) {
return Object.getOwnPropertyNames(value).reduce(
function (error: any, key: string) {
error[key] = value[key]; // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Error'. No index signature with a parameter of type 'string' was found on type 'Error'.
return error;
},
{}
);
}
return value;
}

...

catch (error) {
log.error(`${JSON.stringify(error, replaceErrors)}`);
if (
error.properties &&
error.properties.errors instanceof Array
) {
const errorMessages = error.properties.errors
.map(function (error: Error) {
return error.properties.explanation; // Property 'properties' does not exist on type 'Error'.
})
.join("\n");
console.log("errorMessages", errorMessages);
/*
* errorMessages is a humanly readable message looking like this:
* 'The tag beginning with "foobar" is unopened'
*/
}
throw error;
}



Подробнее здесь: https://stackoverflow.com/questions/795 ... typescript
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»