pleroma-fe/src/services/errors/errors.js

68 lines
2.1 KiB
JavaScript
Raw Normal View History

import { capitalize } from 'lodash'
2026-01-06 16:22:52 +02:00
function humanizeErrors(errors) {
return Object.entries(errors).reduce((errs, [k, val]) => {
const message = val.reduce((acc, message) => {
const key = capitalize(k.replace(/_/g, ' '))
return acc + [key, message].join(' ') + '. '
}, '')
return [...errs, message]
}, [])
}
2026-01-06 16:22:52 +02:00
export function StatusCodeError(statusCode, body, options, response) {
2019-02-26 12:26:04 -05:00
this.name = 'StatusCodeError'
this.statusCode = statusCode
2026-01-06 16:22:52 +02:00
this.message =
statusCode + ' - ' + (JSON && JSON.stringify ? JSON.stringify(body) : body)
2019-02-26 12:26:04 -05:00
this.error = body // legacy attribute
this.options = options
this.response = response
2026-01-06 16:22:52 +02:00
if (Error.captureStackTrace) {
// required for non-V8 environments
2019-02-26 12:26:04 -05:00
Error.captureStackTrace(this)
}
}
StatusCodeError.prototype = Object.create(Error.prototype)
StatusCodeError.prototype.constructor = StatusCodeError
export class RegistrationError extends Error {
2026-01-06 16:22:52 +02:00
constructor(error) {
super()
if (Error.captureStackTrace) {
Error.captureStackTrace(this)
}
try {
// the error is probably a JSON object with a single key, "errors", whose value is another JSON object containing the real errors
if (typeof error === 'string') {
error = JSON.parse(error)
2022-07-31 12:36:02 +03:00
// eslint-disable-next-line
2026-01-06 16:20:14 +02:00
if (Object.hasOwn(error, 'error')) {
error = JSON.parse(error.error)
}
}
if (typeof error === 'object') {
const errorContents = JSON.parse(error.error)
// keys will have the property that has the error, for example 'ap_id',
// 'email' or 'captcha', the value will be an array of its error
// like "ap_id": ["has been taken"] or "captcha": ["Invalid CAPTCHA"]
// replace ap_id with username
if (errorContents.ap_id) {
errorContents.username = errorContents.ap_id
delete errorContents.ap_id
}
this.message = humanizeErrors(errorContents)
} else {
this.message = error
}
2025-02-04 15:23:21 +02:00
} catch {
// can't parse it, so just treat it like a string
this.message = error
}
}
}