jonschlinkert / gray-matter

Smarter YAML front matter parser, used by metalsmith, Gatsby, Netlify, Assemble, mapbox-gl, phenomic, vuejs vitepress, TinaCMS, Shopify Polaris, Ant Design, Astro, hashicorp, garden, slidev, saber, sourcegraph, and many others. Simple to use, and battle tested. Parses YAML by default but can also parse JSON Front Matter, Coffee Front Matter, TOML Front Matter, and has support for custom parsers. Please follow gray-matter's author: https://github.com/jonschlinkert
https://github.com/jonschlinkert
MIT License
3.91k stars 138 forks source link

Expose `YAMLException` from `js-yaml` #169

Open andreww2012 opened 8 months ago

andreww2012 commented 8 months ago

I find YAMLExceptions too big when the parsed front matter is big because they include the whole source text. I decided to reformat an error a bit, for that I had to catch the parsing error using the obvious approach:

import parseMdWithFrontMatter from 'gray-matter';
import {YAMLException} from 'js-yaml';

try {
  const parsedContents = parseMdWithFrontMatter(contents);
  // ...
} catch (error) {
  if (error instanceof YAMLException) {
    // Format the error ...
  }
  throw error;
}

However, I was surprised when the error wasn't caught. It turned out I have my own js-yaml of a different major version (4.1.0), so technically imported YAMLException was a different class.

I think for cases like this, importing (at least) YAMLException from underlying gray-matter would be beneficial. Although, feel free to correct me if I'm doing something wrong. And thank you for the lib! :)

P.S. My workaround: ```js import grayMatter from 'gray-matter'; import {YAMLException} from 'js-yaml'; export const parseMdWithFrontMatter = (...args: Parameters) => { try { return grayMatter(...args); } catch (error) { if (error && typeof error === 'object' && error.constructor?.name === 'YAMLException') { Object.setPrototypeOf(error, YAMLException.prototype); } throw error; } }; ```