The result of the callback function or the default if an exception occurred calling the callback function.
let theExpression = "{ invalid: json value";
let result = safeGet(() => {
return JSON.parse(theExpression);
}, {});
// result === {};
// Example with arguments
let result = safeGet((id: number, name: string) => {
if (id <= 0) {
throw new Error("Invalid ID");
}
return { id, name };
}, { id: 0, name: "default" }, [-1, "test"]);
// result === { id: 0, name: "default" };
// Example with arguments successfully used
const result = safeGet((a: number, b: number) => {
return a + b;
}, 0, [5, 10]);
// result === 15
// Example accessing nested properties safely
const config = { database: null };
const connectionString = safeGet(() => {
return config.database.connectionString;
}, "default_connection");
// Since config.database is null, accessing connectionString would throw
// connectionString === "default_connection"
Function to safely execute a callback function, if the function throws the provided default value will be returned.