Skip to content

[Feature]: Subtype PlaywrightException in the case of failing assertions #2940

Closed

Description

🚀 Feature Request

Playwright exceptions that come from Expects would be be subtyped.

public sealed class PlaywrightAssertionException : PlaywrightException
{
    public PlaywrightAssertionException()
    {
    }

    public PlaywrightAssertionException(string message) : base(message)
    {
    }

    public PlaywrightAssertionException(string message, Exception innerException) : base(message, innerException)
    {
    }

Example

No response

Motivation

I am following the guidance of `Expect'- first assertions and migrating away from NUnit assertions in the process. However, it was useful to me to know when a test failed because of an assertion exception, or when the test was was improperly crafted.

I am happy to implement this feature myself.

Activity

  1. dcrousso commented on Oct 21, 2026

    @dcrousso
    Contributor

    Hi, the Playwright bot investigated this on my behalf.

    A distinct assertion exception is not currently available. Failed Expect calls still throw PlaywrightException, including through the NUnit base classes. Custom expect messages add context but do not provide a separate exception type.

    Should the proposed subtype identify only unmet expectations, leaving invalid selectors and other execution failures as ordinary errors, or every failure from Expect? Invalid selectors and strict mode violations currently use the same assertion failure formatting, so changing the exception type alone would still classify some improperly crafted tests as assertion failures.

    Evidence and acceptance criteria
    • Inspected current main at 9eac4c8456fdf60f01df5e0dc58f4ebe64239781. This was a source and documentation review. No builds or tests were run.
    • Locator and page assertions construct PlaywrightException in
      var result = await CallExpectAsync(expression, expectOptions, title).ConfigureAwait(false);
      if (result.Matches == IsNot)
      {
      var actual = result.Received;
      var log = Connection.FormatCallLog(result.Log);
      if (result.ErrorMessage != null)
      {
      message += "\n" + result.ErrorMessage;
      }
      var ariaSnapshotSuffix = string.IsNullOrEmpty(result.ReceivedAriaSnapshot) ? string.Empty : $"\nAria snapshot:\n{result.ReceivedAriaSnapshot}";
      var prefix = CustomMessage != null ? CustomMessage + "\n\n" : string.Empty;
      if (expected == null)
      {
      throw new PlaywrightException($"{prefix}{message} {log}{ariaSnapshotSuffix}");
      }
      throw new PlaywrightException($"{prefix}{message} '{FormatValue(expected)}'\nBut was: '{FormatValue(actual)}' {log}{ariaSnapshotSuffix}");
      }
      . Response assertions have a separate throw site in
      public IAPIResponseAssertions Not => new APIResponseAssertions(_actual, !_isNot, _customMessage);
      public async Task ToBeOKAsync()
      {
      if (_actual.Ok == !_isNot)
      {
      return;
      }
      var message = $"Response status expected to be within [200..299] range, was {_actual.Status}";
      if (!_isNot)
      {
      message = message.Replace("expected to", "expected not to");
      }
      var logList = await _actual.FetchLogAsync().ConfigureAwait(false);
      message += Connection.FormatCallLog(logList);
      var contentType = _actual.Headers.TryGetValue("content-type", out var contentTypeValue) ? contentTypeValue : string.Empty;
      bool isTextEncoding = IsTextualMimeType(contentType);
      var responseText = string.Empty;
      if (isTextEncoding)
      {
      var text = await _actual.TextAsync().ConfigureAwait(false);
      if (!string.IsNullOrEmpty(text))
      {
      var trimmedText = text.Length > 1000 ? text.Substring(0, 1000) : text;
      responseText = $"\nResponse text:\n{trimmedText}";
      }
      }
      var prefix = _customMessage != null ? _customMessage + "\n\n" : string.Empty;
      throw new PlaywrightException(prefix + message + responseText);
      }
      private static bool IsTextualMimeType(string contentType)
      {
      if (string.IsNullOrEmpty(contentType))
      .
    • Existing StrictModeViolationErrorFormat and InvalidSelectorErrorFormat cases demonstrate the classification boundary that needs a decision:
      [PlaywrightTest("page/expect-misc.spec.ts", "strict mode violation error format")]
      public async Task StrictModeViolationErrorFormat()
      {
      await Page.SetContentAsync(@"<div>hello</div><div>hi</div>");
      var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Expect(Page.Locator("div")).ToBeVisibleAsync());
      StringAssert.Contains("Locator expected to be visible", exception.Message);
      StringAssert.Contains("Error: strict mode violation: Locator(\"div\") resolved to 2 elements:", exception.Message);
      }
      [PlaywrightTest("page/expect-misc.spec.ts", "invalid selector error format")]
      public async Task InvalidSelectorErrorFormat()
      {
      await Page.SetContentAsync(@"<div>a</div><div>b</div>");
      var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Expect(Page.Locator("##")).ToBeVisibleAsync());
      StringAssert.Contains("Locator expected to be visible", exception.Message);
      StringAssert.Contains("Error: Unexpected token \"#\" while parsing css selector \"##\".", exception.Message);
      }
      .
    • The NUnit wrapper forwards directly to core assertions, without translating exceptions:
      public static void SetDefaultExpectTimeout(float timeout) => Assertions.SetDefaultExpectTimeout(timeout);
      public ILocatorAssertions Expect(ILocator locator) => Assertions.Expect(locator);
      public IPageAssertions Expect(IPage page) => Assertions.Expect(page);
      public IAPIResponseAssertions Expect(IAPIResponse response) => Assertions.Expect(response);
      public ILocatorAssertions Expect(ILocator locator, string message) => Assertions.Expect(locator, message);
      public IPageAssertions Expect(IPage page, string message) => Assertions.Expect(page, message);
      public IAPIResponseAssertions Expect(IAPIResponse response, string message) => Assertions.Expect(response, message);
      . A subtype of PlaywrightException would not itself be NUnit's AssertionException: https://docs.nunit.org/api/NUnit.Framework.AssertionException.html.
    • The official example still shows Microsoft.Playwright.PlaywrightException: https://playwright.dev/dotnet/docs/test-assertions#custom-expect-message. The merged custom message change did not add a subtype: feat(assertions): support custom expect message #3309.
    • Once the boundary is agreed, an acceptance check can extend existing ShouldSupportToBeChecked with an exact subtype assertion while retaining its message checks and base exception compatibility. Existing invalid selector and strict mode cases should pin the chosen boundary, and the existing response failure case should cover its separate throw site. These are proposed checks, not executed results.

    The issue remains marked P3-collecting-feedback, with no comments, linked PR, or recorded approval of the API design in its timeline.

  2. RenderMichael commented on Oct 21, 2026

    @RenderMichael
    ContributorAuthor

    Sounds like the bot needs to learn that a feature request asks for something that is, by definition, not currently available 😅

    The latter half of the response implies some technical difficulties, but they seem surmountable to me. I don't think there was ever a question of technical feasibility here, only one of design.

  3. github-actions commented on Nov 2, 2026

    @github-actions

    Hi, I'm the Playwright bot. I started to triage this issue on Linux: agent run

  4. github-actions commented on Nov 4, 2026

    @github-actions

    Hi, I'm the Playwright bot. I started to triage this issue on Linux: agent run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions