Skip to content

Commit

Permalink
Add RobloxAPIError class (#841)
Browse files Browse the repository at this point in the history
* Create extremely basic error class

* Make most of class

* Fix typo
  • Loading branch information
Regalijan authored Dec 12, 2024
1 parent 88c9f61 commit efb89d8
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions lib/util/apiError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// The data should be a response object

class RobloxAPIError extends Error {
constructor (data) {
super(getResponseBody(data))

this.name = 'RobloxAPIError'
this.httpStatusCode = data.statusCode
this.responseBody = getResponseBody(data)
}

get error () {
let obj

try {
obj = JSON.parse(this.responseBody)
} catch {
return { code: 0, message: this.responseBody.toString() }
}

if (Object.hasOwn(obj, 'error')) return obj.error // V1 open cloud and some very old BEDEV1 endpoints + some global errors

else if (Object.hasOwn(obj, 'errors')) { // Most BEDEV1 endpoints
return obj.errors.at(0) // In spite of BEDEV1 endpoint errors being nested in an array, they are never seen in groups.
} else if (Object.hasOwn(obj, 'code') && Object.hasOwn(obj, 'message')) { // V2 open cloud
return obj
} else return { code: 0, message: this.responseBody } // Roblox did a funny (i.e. the platform is down)
}
}

function getResponseBody (data) {
if (typeof data.body === 'string') return data.body

try {
return JSON.stringify(data.body)
} catch {
throw Error('The passed response body is not a valid object')
}
}

export default RobloxAPIError

0 comments on commit efb89d8

Please sign in to comment.