diff --git a/admin/src/api.js b/admin/src/api.js index 8467ef6..6897e65 100644 --- a/admin/src/api.js +++ b/admin/src/api.js @@ -10,12 +10,22 @@ export function apiGet(path) { .catch(e => { throw new Error(e.message) }) } +// HTTP 非 2xx 时抛出服务端返回的错误信息(否则 409/500 被当正常 JSON 处理) +function handleResponse(r) { + return r.json().then(j => { + if (!r.ok) { + throw new Error(j.error || j.message || `请求失败(${r.status})`) + } + return j + }) +} + export function apiPost(path, body) { return fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }, body: JSON.stringify(body) - }).then(r => r.json()) + }).then(handleResponse) } export function apiPut(path, body) { @@ -23,12 +33,12 @@ export function apiPut(path, body) { method: 'PUT', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }, body: JSON.stringify(body) - }).then(r => r.json()) + }).then(handleResponse) } export function apiDelete(path) { return fetch(path, { method: 'DELETE', headers: { Authorization: `Bearer ${getToken()}` } - }).then(r => r.json()) + }).then(handleResponse) }