design patterns: should a function generate exceptions based on its expected behavior or its objective state?

My co-worker and I are discussing the correct design for an API. Let's say we have a function void deleteBlogPost(int postId). What should this function do if the blog post is indexed with postId does not exist?

I think it would be appropriate to throw an exception, because the function should be designed to do one thing. When the user calls a function called deleteBlogPost, always await publication with ID postId to be deleted To try to delete a post with an invalid postId It makes no sense, so an exception must be thrown.

My colleague argues that the caller does not really intend to Remove a specific publication, just to ensure that after the call, the publication does not exist. If you call deleteBlogPost With a non-existent publication ID, the goal status has already been reached, so nothing should happen. He also noted that this design guarantees calls to deleteBlogPost They are idempotent, but I am not convinced that this is a good thing.

We find examples of both patterns in several APIs. For example, compare deleting a dictionary / map entry with a key that does not exist between Python and Java:

Piton:

my_dict = {}
del my_dict('test')   # KeyError: 'test'

Java:

Map map = new HashMap<>();
map.remove("test");   // no exception thrown

Should a function throw exceptions based on its expected behavior or its objective state?

exceptions: handling errors in the Nest service layer

I would like to create a REST API with NestJs. But I want to add GraphQL as another higher level layer later. So, for starters, I have the basic layer controller, the service and the TypeORM repository. Suppose you want to update a user's username by id. The controller path could be

PATCH /users/:id/username

Two problems may arise in the service or repository layer:

  • User ID may not exist
  • Username already exist

The basic flow of this operation would be

  • Get the user by id
  • Handle error if the user does not exist
  • Check if the username already exists
  • Handle error if username already exists
  • Update the user's username

I'm thinking about how I should handle those mistakes. I could throw exceptions immediately based on this concept

https://en.wikipedia.org/wiki/Fail-fast

NestJs provides some ready-to-use exceptions that I can use

https://docs.nestjs.com/exception-filters#built-in-http-exceptions

The problem is that I don't think I should throw HTTP exceptions in my service layer. They must be thrown into the logic of my controller. So what is a common approach to those mistakes?

  • I must return? undefined instead of an updated user? The controller would not know which part failed.
  • Should I create my own exceptions by extending Error and throw them away?
  • Due to the fact that exceptions come with poor performance if the return type of the function is something like ?

Authentication: result object against launch exceptions

When sending a request to another module and expecting a result, it seems to me that there are two ways to deal with the & # 39; roads not happy & # 39 ;.

  • Throw an exception
  • Returns a result object that involves different results (such as value and error)

I would say the first seems better overall. It keeps the code clean and readable. If you expect the result to be correct, simply start an exception to handle the happy route divergence.

But what happens when you have no idea what the result will be?

For example, call a module that validates a lottery ticket. The happy way would be that you won, but it probably won't be. Would it be better to consider that the happy path is getting a result of the LotteryTicketValidator And it only handles the exceptions for when the ticket could not be processed?

Another could be user authentication at login. Can we assume that the user entered the correct credentials and throw an exception when the credentials are invalid, or should we expect to obtain some type of LoginResult object?

Opinion about Python exceptions? – Code review stack exchange

Just looking for opinions on what is the best way to use exceptions?

If exception handling enters the function or you must exit the function when the function is actually called. For example, we could have the following function:

def divideMe(a,b):

     return a/b

This function is risky because there is a possibility that if the program making the call passes a value of 0 for argument b, the function would be divided by zero and an exception would be generated. So, the question is whether you should put exception handling inside the function and handle it like this:

def divideMe(a,b):

     try:

          return a/b

     except Exception:

          return 0

Or if the program making the call detects and handles the exception, like this:

try:

   result = divideMe(x,y)

except Exception:

   print("You entered 0 in for denominator")

Java: automated code navigation to find all kinds of exceptions?

There is a java code base based on the Spring Boot framework. As an activity, I want to navigate the code path of each API method to verify verified exceptions that are thrown at different points in the code path.

I am now aware that the exceptions thrown in the code path would have to be captured and handled or sent to the caller, but the problem here is that I have a base class for exceptions thrown by the application that is caught or thrown by The API Methods As a result, I don't know about the particular exceptions that can be expected in the method call chain. Below you will find an example of simple code to complement my problem statement:

class Controller { 
    public void apiMethod() throws CustomException {
        Service service = new Service();
        service.method1();//throws CustomException1
        service.method2();//throws CustomException2
    }
}

class Service {
    public void method1() throws CustomException1 {
        throw new CustomException1();   
    }

    public void method2() throws CustomException2 {
        throw new CustomException2();

    }
}

class CustomException extends Exception {

}

class CustomException1 extends CustomException {

}

class CustomException2 extends CustomException {

}

As is clear from the code, the API method is aware that type exceptions Custom exception It would be thrown by the call chain, but is not aware of the exact exceptions that can be thrown. Now I want to know an automated way to do this.

Let me know if you need more information or clarity.

php – Manage exceptions within MVC

I developed an MVC model for my project. Within Core, I would like to know how to manage when, for example, if the user writes a driver that does not exist in the URL, how can I forward it to an error page?

In my code, when the user writes, for example, localhost / myproject / city, and City Controller does not exist, it returns an error

Warning: call_user_func_array () expects parameter 1 to be a valid callback, class & # 39; homeController & # 39; does not have a method & # 39; & # 39; in C: Program Files VertrigoServ www core core.php on line 61

Below is my full core

Core class {

public function run() {
    //Pegar o que o usuario digitou
    //$url = substr($_SERVER('PHP_SELF'), 25);
$url = substr($_SERVER('PHP_SELF'), 10);


// Se o usuario digitar qualquer coisa, vout transformar em arrya
$params = array ();
if (!empty($url)) {
    $url = explode("/", $url);

    array_shift($url);


    if (isset($url(1))) {
        $currentController = $url('1')."Controller";
    } else {
        $currentController = "homeController";
    }       


    if (isset($url(2))) {
        //Isso é uma action
            $currentAction = $url(2);   
    } else {
        $currentAction = "index";
    }

        if (count($url) > 0) {
        $params = $url;
            }
        } else {
            $currentController = "homeController";
            $currentAction = "index";
        }

        require_once 'core/controller.php';
        $c = New $currentController();
        call_user_func_array(array($c,$currentAction), $params);

}

}
?>

design patterns: why don't exceptions & # 39; fools & # 39 ;, be detected especially in the server code?

I am confused because in many places I have already read that we are not supposed to detect the so-called exceptions & # 39; fools & # 39; (those resulting from errors in the code). Instead, they should be allowed to block the application:

At least two of the three persons mentioned are established authorities.

I'm surprised. Especially for some use cases (important!), Like the server-side code, I just can't see why it is capturing such a suboptimal exception and why the application should be allowed to crash.

As far as I know, the typical solution in this case is to detect the exception, return HTTP 500 to the client, have an automatic system that sends an emergency email to the development team so that they can solve the problem as soon as possible, but Do not do block the application (a request must fail, there is nothing we can do here, but why disable all the service and make it impossible for everyone else to use our website? Downtime is expensive!). Am i wrong

Why i ask? I perpetually try to finish a hobby project, which is a browser-based game in .net core. To my knowledge, in many cases, the framework does it for me Outside the Box Against what Eric Lippert and Stephen Cleary are recommending against! – that is, if a request is handled, the framework automatically detects the exception and prevents the server from failing. In some places, however, the framework does not do this. In such places, I am wrapping my own code with try {...} catch {...} to catch all possible exceptions & # 39; fools & # 39 ;.

One of those places, AFAIK, is background tasks. For example, I am now implementing a fund ban removal service that is supposed to erase all expired temporary bans every few minutes. Here, I'm even wearing some layers of everything try blocks:

try // prevent server from crashing if boneheaded exception occurs here
{
    var expiredBans = GetExpiredBans();
    foreach(var ban in expiredBans)
    {
        try // If removing one ban fails, eg because of a boneheaded problem, 
        {   // still try to remove other bans
            RemoveBan(ban);
        }
        catch
        {

        }
    }
}
catch
{

}

(If my catch the blocks are empty at the moment: I am aware that ignoring these exceptions is unacceptable, adding some record is perpetually on my ALL list)

After reading the articles that I have linked previously, I can no longer do this without any serious doubt … Am I not shooting myself in the foot? Why? Why not?

If and why should never be caught insane exceptions?

exceptions – NullReferenceException in Unity

Value type vs reference type

In many programming languages, variables have what is called a "type of data." The two main data types are the value types (int, float, bool, char, struct, …) and the reference type (class instance). While the value types contain the value itself, references contains a memory address pointing to a portion of memory allocated to contain a set of values ​​(similar to C / C ++).

For example, Vector3 It is a type of value (a structure that contains the coordinates and some functions) while the components attached to your GameObject (including your custom scripts inherited from MonoBehaviour) are of the reference type.

When can I have a NullReferenceException?

NullReferenceException they are released when you try to access a reference variable that does not reference any object, therefore it is null (the memory address points to 0).

Some common places to NullReferenceException It will be considered:

Manipulate a GameObject / Component that has not been specified in the inspector

// t is a reference to a Transform.
public Transform t ;

private void Awake()
{
     // If you do not assign something to t
     // (either from the Inspector or using GetComponent), t is null!
     t.Translate();
}

Retrieving a component that is not connected to the GameObject and then trying to manipulate it:

private void Awake ()
{
    // Here, you try to get the Collider component attached to your gameobject
    Collider collider = gameObject.GetComponent();

    // But, if you haven't any collider attached to your gameobject,
    // GetComponent won't find it and will return null, and you will get the exception.
    collider.enabled = false ;
}

Access a GameObject that does not exist:

private void Start()
{
    // Here, you try to get a gameobject in your scene
    GameObject myGameObject = GameObject.Find("AGameObjectThatDoesntExist");

    // If no object with the EXACT name "AGameObjectThatDoesntExist" exist in your scene,
    // GameObject.Find will return null, and you will get the exception.
    myGameObject.name = "NullReferenceException";
}

Note: Be careful, GameObject.Find, GameObject.FindWithTag, GameObject.FindObjectOfType only return game objects that are enabled in the hierarchy when the function is called.

Trying to use the result of a gettingter that is returning null:

var fov = Camera.main.fieldOfView;
// main is null if no enabled cameras in the scene have the "MainCamera" tag.

var selection = EventSystem.current.firstSelectedGameObject;
// current is null if there's no active EventSystem in the scene.

var target = RenderTexture.active.width;
// active is null if the game is currently rendering straight to the window, not to a texture.

Access an element of an uninitialized array

private GameObject() myObjects ; // Uninitialized array

private void Start()
{
    for( int i = 0 ; i < myObjects.Length ; ++i )
        Debug.Log( myObjects(i).name ) ;
}

Less common, but annoying if you don't know about C # delegates:

delegate double MathAction(double num);

// Regular method that matches signature:
static double Double(double input)
{
    return input * 2;
}

private void Awake()
{
    MathAction ma ;

    // Because you haven't "assigned" any method to the delegate,
    // you will have a NullReferenceException
    ma(1) ;

    ma = Double ;

    // Here, the delegate "contains" the Double method and
    // won't throw an exception
    ma(1) ;
}

How to fix ?

If you have understood the previous paragraphs, you know how to correct the error: make sure that your variable references (points to) an instance of a class (or that it contains at least one function for delegates).

Easier said than done? Yes actually. Here are some tips for avoid Y identify the problem.

The "dirty" way: the try & catch method:

Collider collider = gameObject.GetComponent();

try
{
    collider.enabled = false ;
}       
catch (System.NullReferenceException exception) {
    Debug.LogError("Oops, there is no collider attached", this) ;
}

The "cleanest" way (in my humble opinion): the check

Collider collider = gameObject.GetComponent();

if(collider != null)
{
    // You can safely manipulate the collider here
    collider.enabled = false;
}    
else
{
    Debug.LogError("Oops, there is no collider attached", this) ;
}

When you face an error that you cannot solve, it is always A good idea to find the cause of the problem. If it is "lazy" (or if the problem can be easily solved), use Debug.Log to display information on the console that will help you identify what may cause the problem. A more complex way is to use the breakpoints and debugger of your IDE.

Using Debug.Log It is quite useful to determine which function is called first, for example. Especially if it has a function responsible for initializing fields. But don't forget to remove those Debug.Log to avoid cramming your console (and for performance reasons).

Another tip, feel free to "cut" your function calls and add Debug.Log to make some checks

Instead of :

 GameObject.Find("MyObject").GetComponent().value = "foo" ;

Do this to verify if all references are established:

GameObject myObject = GameObject.Find("MyObject") ;

Debug.Log( myObject ) ;

MySuperComponent superComponent = myObject.GetComponent() ;

Debug.Log( superComponent ) ;

superComponent.value = "foo" ;

Even better :

GameObject myObject = GameObject.Find("MyObject") ;

if( myObject != null )
{
   MySuperComponent superComponent = myObject.GetComponent() ;
   if( superComponent != null )
   {
       superComponent.value = "foo" ;
   }
   else
   {
        Debug.Log("No SuperComponent found onMyObject!");
   }
}
else
{
   Debug.Log("Can't find MyObject!", this ) ;
}

Sources:

  1. http://answers.unity3d.com/questions/47830/what-is-a-null-reference-exception-in-unity.html
  2. https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it/218510#218510
  3. https://support.unity3d.com/hc/en-us/articles/206369473-NullReferenceException
  4. https://unity3d.com/fr/learn/tutorials/topics/scripting/data-types

design: c ++ exceptions, should the caller add the context or provide it to the caller?

Here is a code snippet. Basically, I upload some source files, all of them are compiled separately and then I link them.

LinkedObject loadObject(std::vector& fileNames)
{
    for(const std::string& fileName : fileNames)
    {
        std::string source = loadSourceFromFile(fileName);
        objects.push_back(CompiledObject(fileName, source));
    }
    return LinkedObject(fileNames, objects);
}

loadSourceFromFile needs the name of the file and will generate an exception with a precise message of what happens and what file.

CompiledObject and LinkedObject will do the same, but they don't need the file names. So I pass them as arguments just in order to give more context to the exception messages.

Of course, other types of exceptions can be thrown in the process.

Maybe it doesn't matter for this example, since the "context" here is only one / several strings, but I don't like it. In my view, the caller must be responsible for adding the context if the caller does not have access to that.

But this is the only sensible way I have found not to contaminate the function with code related to errors. Other ways would require you to add several try / catch blocks and define exception types.

LinkedObject loadObject(std::vector& fileNames)
{
    try
    {
        for(const std::string& fileName : fileNames)
        {
            std::string source = loadSourceFromFile(fileName);

            try
            {
                objects.push_back(CompiledObject(fileName, source));
            }
            catch(CustomException& e)
            {
                // throw std::runtime_error with more context
            }
        }
        return LinkedObject(fileNames, objects);
    }
    catch(CustomException& e)
    {
        // rethrow std::runtime_error with more context
    }

}

Which is much less readable than the previous one and requires custom exception types.

Should the caller handle the context, at the cost of having a harder code to read? Or should the caller provide the context? Or maybe I am not using the correct error handling mechanism in this case, and should I use something else (for example, std :: expected)?

Exceptions – Exception java.util.stream.ReferencePipeline $ 2 is in module java.base of loader 'bootstrap'

I tell you, I have to implement an onClick method for the following button:

Well, in the method that I have implemented is the following:

@FXML
private void FilterList() throws IOException{

    List players = guiApp.getController().getPlayersByName(searchId.getText());     
    displayPlayers(players);
}

GetPlayersByName simulates a database call:

public List getPlayersByName(String name){
    List response=new ArrayList();

    for(Team t : this.getTeams()) 
    {
        response.add((Player) t.getSquad().stream().filter((o->o.getName().contains(name)|| o.getSurname().contains(name))));
    }
    return response;
}

The problem comes that when executing it I get the following exception:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1787)
    at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3564)
    at javafx.graphics/javafx.scene.Scene$ClickGenerator.access$8200(Scene.java:3492)
    at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3860)
    at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1200(Scene.java:3579)
    at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1849)
    at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2588)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:397)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:434)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:390)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:433)
    at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
    at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1784)
    ... 33 more
Caused by: java.lang.ClassCastException: class java.util.stream.ReferencePipeline$2 cannot be cast to class edu.uoc.baluocesto.model.Player (java.util.stream.ReferencePipeline$2 is in module java.base of loader 'bootstrap'; edu.uoc.baluocesto.model.Player is in unnamed module of loader 'app')
    at edu.uoc.baluocesto.controller.Database.getPlayersByName(Database.java:214)
    at edu.uoc.baluocesto.view.gui.MainMenuController.FilterList(MainMenuController.java:137)
    ... 44 more

And I have no idea how to fix it, can you think of an idea?