0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-03-31 22:51:25 -05:00

refactor(core,console,phrases): fix connector error handling and phrases (#3488)

This commit is contained in:
Gao Sun 2023-03-18 20:57:05 +08:00 committed by GitHub
parent c312bd4d88
commit 97985da522
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 49 additions and 46 deletions

View file

@ -1,5 +0,0 @@
@use '@/scss/underscore' as _;
.senderTest {
margin-top: _.unit(6);
}

View file

@ -19,7 +19,6 @@ import { initFormData, parseFormConfig } from '@/pages/Connectors/components/Con
import type { ConnectorFormType } from '@/pages/Connectors/types';
import { SyncProfileMode } from '@/pages/Connectors/types';
import * as styles from './ConnectorContent.module.scss';
import SenderTester from './SenderTester';
type Props = {
@ -136,7 +135,6 @@ const ConnectorContent = ({ isDeleted, connectorData, onConnectorUpdated }: Prop
{connectorData.type !== ConnectorType.Social && (
<FormCard title="connector_details.test_connection">
<SenderTester
className={styles.senderTest}
connectorId={connectorData.id}
connectorType={connectorData.type}
config={watch('config')}

View file

@ -69,9 +69,12 @@ const SenderTester = ({ connectorId, connectorType, config, className }: Props)
const data = { config: result.data, ...(isSms ? { phone: sendTo } : { email: sendTo }) };
await api.post(`api/connectors/${connectorId}/test`, { json: data }).json();
setShowTooltip(true);
try {
await api.post(`api/connectors/${connectorId}/test`, { json: data }).json();
setShowTooltip(true);
} catch (error: unknown) {
console.error(error);
}
});
return (

View file

@ -15,6 +15,7 @@ const formatZodError = ({ issues }: ZodError): string[] =>
return base + issue.message;
});
export default class RequestError extends Error {
code: LogtoErrorCode;
status: number;

View file

@ -108,7 +108,7 @@ describe('koaConnectorErrorHandler middleware', () => {
new RequestError(
{
code: 'connector.template_not_found',
status: 500,
status: 400,
},
{ message }
)
@ -198,7 +198,7 @@ describe('koaConnectorErrorHandler middleware', () => {
new RequestError(
{
code: 'connector.general',
status: 500,
status: 400,
},
{ message }
)
@ -216,7 +216,7 @@ describe('koaConnectorErrorHandler middleware', () => {
new RequestError(
{
code: 'connector.general',
status: 500,
status: 400,
errorDescription: '\nMock General connector errors',
},
message

View file

@ -1,5 +1,5 @@
import { ConnectorError, ConnectorErrorCodes } from '@logto/connector-kit';
import { conditional } from '@silverhand/essentials';
import { trySafe } from '@silverhand/essentials';
import type { Middleware } from 'koa';
import { z } from 'zod';
@ -8,7 +8,7 @@ import RequestError from '#src/errors/RequestError/index.js';
export default function koaConnectorErrorHandler<StateT, ContextT>(): Middleware<StateT, ContextT> {
// Too many error types :-)
// eslint-disable-next-line complexity
return async (ctx, next) => {
return async (_, next) => {
try {
await next();
} catch (error: unknown) {
@ -19,8 +19,7 @@ export default function koaConnectorErrorHandler<StateT, ContextT>(): Middleware
const { code, data } = error;
const errorDescriptionGuard = z.object({ errorDescription: z.string() });
const result = errorDescriptionGuard.safeParse(data);
const errorMessage = conditional(result.success && '\n' + result.data.errorDescription);
const message = trySafe(() => errorDescriptionGuard.parse(data))?.errorDescription;
switch (code) {
case ConnectorErrorCodes.InvalidMetadata:
@ -43,7 +42,7 @@ export default function koaConnectorErrorHandler<StateT, ContextT>(): Middleware
throw new RequestError(
{
code: `connector.${code}`,
status: 500,
status: 400,
},
data
);
@ -57,8 +56,8 @@ export default function koaConnectorErrorHandler<StateT, ContextT>(): Middleware
throw new RequestError(
{
code: `connector.${code}`,
status: 500,
errorDescription: errorMessage,
status: 400, // Temporarily use 400 to avoid false positives. May update later.
errorDescription: message,
},
data
);

View file

@ -98,7 +98,7 @@ const errors = {
},
connector: {
// UNTRANSLATED
general: 'An unexpected error occurred in connector.{{errorDescription}}',
general: 'Error occurred in connector: {{errorDescription}}',
not_found: 'Cannot find any available connector for type: {{type}}.',
not_enabled: 'The connector is not enabled.',
invalid_metadata: "The connector's metadata is invalid.",

View file

@ -14,8 +14,9 @@ const connector_details = {
test_sms_sender: 'Teste den SMS Connector',
test_email_placeholder: 'Gib eine Test-E-Mail ein',
test_sms_placeholder: 'Gib eine Test-Telefonnummer ein',
test_message_sent: 'Testnachricht wurde gesendet!',
test_sender_description: 'Wenn dein JSON richtig konfiguriert ist, erhältst du eine Nachricht.',
test_message_sent: 'Testnachricht wurde gesendet',
test_sender_description:
'Logto verwendet die "Generic"-Vorlage zum Testen. Du erhältst eine Nachricht, wenn dein Connector richtig konfiguriert ist.',
options_change_email: 'E-Mail Connector bearbeiten',
options_change_sms: 'SMS Connector bearbeiten',
connector_deleted: 'Der Connector wurde erfolgreich gelöscht',

View file

@ -97,7 +97,7 @@ const errors = {
'Interaction session not found. Please go back and start the session again.',
},
connector: {
general: 'An unexpected error occurred in connector.{{errorDescription}}',
general: 'Error occurred in connector: {{errorDescription}}',
not_found: 'Cannot find any available connector for type: {{type}}.',
not_enabled: 'The connector is not enabled.',
invalid_metadata: "The connector's metadata is invalid.",

View file

@ -9,13 +9,14 @@ const connector_details = {
save_error_empty_config: 'Please enter config',
send: 'Send',
send_error_invalid_format: 'Invalid input',
edit_config_label: 'Enter your json here',
edit_config_label: 'Enter your JSON here',
test_email_sender: 'Test your email connector',
test_sms_sender: 'Test your SMS connector',
test_email_placeholder: 'Enter a test email address',
test_sms_placeholder: 'Enter a test phone number',
test_message_sent: 'Test message sent!',
test_sender_description: 'You will receive a message if your json is rightly configured',
test_message_sent: 'Test message sent',
test_sender_description:
'Logto uses the "Generic" template for testing. You will receive a message if your connector is rightly configured.',
options_change_email: 'Change email connector',
options_change_sms: 'Change SMS connector',
connector_deleted: 'The connector has been successfully deleted',

View file

@ -16,7 +16,7 @@ const errors = {
password_pattern_error:
'Password requires a minimum of {{min}} characters and contains a mix of letters, numbers, and symbols.',
insecure_contexts: 'Insecure contexts (non-HTTPS) are not supported.',
unexpected_error: 'An unexpected error occurred',
unexpected_error: 'An unexpected error occurred.',
not_found: '404 not found',
create_internal_role_violation:
'You are creating a new internal role which is forbidden by Logto. Try another name that does not start with "#internal:".',

View file

@ -102,7 +102,7 @@ const errors = {
'Interaction session not found. Please go back and start the session again.', // UNTRANSLATED
},
connector: {
general: "Une erreur inattendue s'est produite dans le connecteur. {{errorDescription}}",
general: "Une erreur s'est produite dans le connecteur: {{errorDescription}}",
not_found: 'Impossible de trouver un connecteur disponible pour le type : {{type}}.',
not_enabled: "Le connecteur n'est pas activé.",
invalid_metadata: "The connector's metadata is invalid.", // UNTRANSLATED

View file

@ -14,8 +14,9 @@ const connector_details = {
test_sms_sender: 'Testez votre connecteur SMS',
test_email_placeholder: 'Entrez une adresse email de test',
test_sms_placeholder: 'Entrez un numéro de téléphone de test',
test_message_sent: 'Message de test envoyé !',
test_sender_description: 'Vous recevrez un message si votre json est correctement configuré.',
test_message_sent: 'Message de test envoyé',
test_sender_description:
'Logto utilise le modèle "Generic" pour les tests. Tu recevras un message si ton connecteur est correctement configuré.',
options_change_email: 'Modifier le connecteur Email',
options_change_sms: 'Changer le connecteur SMS',
connector_deleted: 'Le connecteur a été supprimé avec succès',

View file

@ -94,7 +94,7 @@ const errors = {
interaction_not_found: '인터렉션 세션을 찾을 수 없어요. 처음부터 다시 세션을 시작해 주세요.',
},
connector: {
general: '연동 중에 알 수 없는 오류가 발생했어요. {{errorDescription}}',
general: '커넥터에서 오류가 발생했습니다: {{errorDescription}}',
not_found: '{{type}} 값을 가진 연동 종류를 찾을 수 없어요.',
not_enabled: '연동이 활성화되지 않았어요.',
invalid_metadata: '연동 메타데이터가 유효하지 않아요.',

View file

@ -14,8 +14,9 @@ const connector_details = {
test_sms_sender: 'SMS 연동 테스트',
test_email_placeholder: '테스트 이메일 주소를 입력해 주세요.',
test_sms_placeholder: '테스트 휴대전화번호를 입력해 주세요.',
test_message_sent: '테스트 메세지 전송 완료!',
test_sender_description: 'JSON 설정이 정확하다면, 메세지를 받을 거에요.',
test_message_sent: '테스트 메세지 전송 완료',
test_sender_description:
'Logto는 "Generic" 템플릿을 사용하여 테스트합니다. 커넥터가 올바르게 구성되면 메시지를 받게 됩니다.',
options_change_email: '이메일 연동 수정',
options_change_sms: 'SMS 연동 수정',
connector_deleted: '연동이 성공적으로 제거되었어요.',

View file

@ -98,7 +98,7 @@ const errors = {
'Interaction session not found. Please go back and start the session again.', // UNTRANSLATED
},
connector: {
general: 'Ocorreu um erro inesperado no conector.{{errorDescription}}',
general: 'Ocorreu um erro no conector: {{errorDescription}}',
not_found: 'Não foi possível encontrar nenhum conector disponível para o tipo: {{type}}.',
not_enabled: 'O conector não está ativado.',
invalid_metadata: 'Os metadados do conector são inválidos.',

View file

@ -14,9 +14,9 @@ const connector_details = {
test_sms_sender: 'Teste seu conector SMS',
test_email_placeholder: 'Insira um endereço de e-mail de teste',
test_sms_placeholder: 'Digite um número de telefone de teste',
test_message_sent: 'Mensagem de teste enviada!',
test_message_sent: 'Mensagem de teste enviada',
test_sender_description:
'Você receberá uma mensagem se seu json estiver configurado corretamente',
'O Logto utiliza o modelo "Generic" para testes. Você receberá uma mensagem se o seu conector estiver configurado corretamente.',
options_change_email: 'Alterar conector de e-mail',
options_change_sms: 'Alterar conector de SMS',
connector_deleted: 'O conector foi excluído com sucesso',

View file

@ -98,7 +98,7 @@ const errors = {
'Interaction session not found. Please go back and start the session again.', // UNTRANSLATED
},
connector: {
general: 'Ocorreu um erro inesperado no conector.{{errorDescription}}',
general: 'Ocorreu um erro no conector: {{errorDescription}}',
not_found: 'Não é possível encontrar nenhum conector disponível para o tipo: {{type}}.',
not_enabled: 'O conector não está ativo.',
invalid_metadata: 'Os metadados do conector são inválidos.',

View file

@ -14,8 +14,9 @@ const connector_details = {
test_sms_sender: 'Teste o conector de SMS',
test_email_placeholder: 'Insira um endereço de email para o teste',
test_sms_placeholder: 'Insira um número de telefone para o teste',
test_message_sent: 'Mensagem de teste enviada!',
test_sender_description: 'Receberá uma mensagem se o JSON estiver configurado corretamente',
test_message_sent: 'Mensagem de teste enviada',
test_sender_description:
'O Logto utiliza o modelo "Generic" para testes. Receberás uma mensagem se o teu conector estiver configurado corretamente.',
options_change_email: 'Alterar conector de email',
options_change_sms: 'Alterar conector de SMS',
connector_deleted: 'O conector foi removido com sucesso',

View file

@ -98,7 +98,7 @@ const errors = {
'Interaction session not found. Please go back and start the session again.', // UNTRANSLATED
},
connector: {
general: 'Bağlayıcıda beklenmeyen bir hata oldu.{{errorDescription}}',
general: 'Bağdaştırıcıda bir hata oluştu: {{errorDescription}}',
not_found: '{{type}} tipi icin uygun bağlayıcı bulunamadı.',
not_enabled: 'Bağlayıcı etkin değil.',
invalid_metadata: "The connector's metadata is invalid.", // UNTRANSLATED

View file

@ -14,8 +14,9 @@ const connector_details = {
test_sms_sender: 'SMS connectorunuzu test edin',
test_email_placeholder: 'Test e-posta adresi girin',
test_sms_placeholder: 'Test telefon numarası girin',
test_message_sent: 'Test mesajı gönderildi!',
test_sender_description: 'Eğer jsonunuz doğru yapılandırılmışsa bir mesaj alacaksınız',
test_message_sent: 'Test mesajı gönderildi',
test_sender_description:
'Logto testler için "Generic" şablonunu kullanır. Bağlantınız doğru şekilde yapılandırılmışsa bir mesaj alacaksınız.',
options_change_email: 'Eposta connectorunuzu değiştirin',
options_change_sms: 'SMS connectorunuzu değiştirin',
connector_deleted: 'Connector başarıyla silindi',

View file

@ -90,7 +90,7 @@ const errors = {
'Interaction session not found. Please go back and start the session again.', // UNTRANSLATED
},
connector: {
general: '连接器发生未知错误{{errorDescription}}',
general: '连接器发生错误{{errorDescription}}',
not_found: '找不到可用的 {{type}} 类型的连接器',
not_enabled: '连接器尚未启用',
invalid_metadata: '连接器 metadata 参数错误',

View file

@ -14,8 +14,9 @@ const connector_details = {
test_sms_sender: '测试你的短信连接器',
test_email_placeholder: '请输入一个用于测试的邮件地址',
test_sms_placeholder: '请输入一个用于测试的手机号码',
test_message_sent: '测试信息已发送!',
test_sender_description: '如果你的 JSON 配置正确,你会收到一条测试消息。',
test_message_sent: '测试信息已发送',
test_sender_description:
'Logto 使用"Generic"模板进行测试。如果你的连接器正确配置,你将收到一条消息。',
options_change_email: '更换邮件连接器',
options_change_sms: '更换短信连接器',
connector_deleted: '成功删除连接器',