Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add NotFound extension. #102

Closed
fiseni opened this issue Apr 28, 2021 · 4 comments
Closed

Add NotFound extension. #102

fiseni opened this issue Apr 28, 2021 · 4 comments

Comments

@fiseni
Copy link
Contributor

fiseni commented Apr 28, 2021

It's a common scenario where we need to validate if a given queried object/entity exists. Instead of checking for null, we can have a more explicit extension for this scenario. We may name it simply NotFound.

The usage will be something like

int id = 1;
Customer myCustomer = customerRepository.GetByID(id);
Guard.Against.NotFound(id, myCustomer, nameof(myCustomer));

We have two options here:

  • We can throw KeyNotFoundException
throw new KeyNotFoundException($"The querried object {objectName} with Key: {key} is not found!");
  • We can add and expose a custom exception NotFoundException in the package.
public class NotFoundException : Exception
{
	public NotFoundException(string key, string objectName) 
		: base($"Queried object {objectName} was not found, Key: {key}")
	{
	}

	public NotFoundException(string key, string objectName, Exception innerException) 
		: base($"Queried object {objectName} was not found, Key: {key}", innerException)
	{
	}
}
@ardalis
Copy link
Owner

ardalis commented Apr 28, 2021

Which do you prefer?

@fiseni
Copy link
Contributor Author

fiseni commented Apr 28, 2021

The custom exception, it's more explicit.
You can then target the exception in try/catch and return NotFound result perhaps?

@ardalis
Copy link
Owner

ardalis commented Apr 28, 2021

Yes, or similar with Ardalis.Result if you don't want the exception to bubble up that far. Wondering if that's something I can build into that package, and how/if it should depend on this one for that exception type...

Want to PR this?

@fiseni
Copy link
Contributor Author

fiseni commented Apr 28, 2021

If Ardalis.Result already depends on GuardClauses, then sure. I have to crosscheck what you have there and how this can be utilized.
But, I wouldn't define the same exception in both packages (in that case they are 2 different exceptions actually).

I'll add the PR later tonight or tomorrow if it's not an issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants