Errors.sys.mjs (2572B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 import { RemoteError } from "chrome://remote/content/shared/RemoteError.sys.mjs"; 6 7 class MessageHandlerError extends RemoteError { 8 /** 9 * @param {(string|Error)=} x 10 * Optional string describing error situation or Error instance 11 * to propagate. 12 */ 13 constructor(x) { 14 super(x); 15 this.name = this.constructor.name; 16 this.status = "message handler error"; 17 18 // Error's ctor does not preserve x' stack 19 if (typeof x?.stack !== "undefined") { 20 this.stack = x.stack; 21 } 22 } 23 24 get isMessageHandlerError() { 25 return true; 26 } 27 28 /** 29 * @returns {Record<string, string>} 30 * JSON serialisation of error prototype. 31 */ 32 toJSON() { 33 return { 34 error: this.status, 35 message: this.message || "", 36 stacktrace: this.stack || "", 37 }; 38 } 39 40 /** 41 * Unmarshals a JSON error representation to the appropriate MessageHandler 42 * error type. 43 * 44 * @param {Record<string, string>} json 45 * Error object. 46 * 47 * @returns {Error} 48 * Error prototype. 49 */ 50 static fromJSON(json) { 51 if (typeof json.error == "undefined") { 52 let s = JSON.stringify(json); 53 throw new TypeError("Undeserialisable error type: " + s); 54 } 55 if (!STATUSES.has(json.error)) { 56 throw new TypeError("Not of MessageHandlerError descent: " + json.error); 57 } 58 59 let cls = STATUSES.get(json.error); 60 let err = new cls(); 61 if ("message" in json) { 62 err.message = json.message; 63 } 64 if ("stacktrace" in json) { 65 err.stack = json.stacktrace; 66 } 67 return err; 68 } 69 } 70 71 /** 72 * A browsing context is no longer available. 73 */ 74 class DiscardedBrowsingContextError extends MessageHandlerError { 75 constructor(message) { 76 super(message); 77 this.status = `discarded browsing context`; 78 } 79 } 80 81 /** 82 * A command could not be handled by the message handler network. 83 */ 84 class UnsupportedCommandError extends MessageHandlerError { 85 constructor(message) { 86 super(message); 87 this.status = "unsupported message handler command"; 88 } 89 } 90 91 const STATUSES = new Map([ 92 ["discarded browsing context", DiscardedBrowsingContextError], 93 ["message handler error", MessageHandlerError], 94 ["unsupported message handler command", UnsupportedCommandError], 95 ]); 96 97 /** @namespace */ 98 export const error = { 99 DiscardedBrowsingContextError, 100 MessageHandlerError, 101 UnsupportedCommandError, 102 };