IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Java EE Discussion :

[Stratégie] Exception se baladant à travers JPA & EJB.. [EJB]


Sujet :

Java EE

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Inscrit en
    Septembre 2008
    Messages
    49
    Détails du profil
    Informations forums :
    Inscription : Septembre 2008
    Messages : 49
    Par défaut [Stratégie] Exception se baladant à travers JPA & EJB..
    Bonjour.

    J'ai une petite problématique sur la gestion d'une exception dans mon application web.

    Dans ma JPA j'ai cela :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    @PrePersist
        @PreUpdate
        private void validateData() {
            if (nom == null || "".equals(nom)) {
                throw new ValidationException("Nom invalide");
            }
            if (prenom == null || "".equals(prenom)) {
                throw new ValidationException("Prénom invalide");
            }
            if (adresse == null || "".equals(adresse)) {
                throw new ValidationException("Adresse invalide");
            }
            if (codePostal == null) {
                throw new ValidationException("Code postal invalide");
            }
            if (ville == null || "".equals(ville)) {
                throw new ValidationException("Ville invalide");
            }
            if (telephone == null || "".equals(telephone)) {
                throw new ValidationException("Téléphone invalide");
            }
            if (motDePasse == null || "".equals(motDePasse)) {
                throw new ValidationException("Mot de passe invalide");
            }
        }
    Du coup lorsque je souhaite rendre persistant mon objet et qu'il y a quelque chose de pas valide, hop j'ai le déclenchement d'une magnifique ValidationException (je l'ai fait hériter de RuntimeException).

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    public class ValidationException extends RuntimeException {
     
        public ValidationException(String error) {
            System.out.println(error);
        }
    }
    Tournons nous vers les EJB maintenant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public Client client_ajout(String nom,
                String prenom,
                String adresse,
                Long codePostal,
                String ville,
                String telephone,
                String motDePasse) throws ValidationException {
            Client c = new Client(nom, prenom, adresse, codePostal, ville, telephone, motDePasse);
            em.persist(c);
            return c;
        }
    Voilà l'exception sera déclenchée ici :
    Le problème c'est que je souhaite me servir de mon exception pour pouvoir afficher un message d'erreur :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    try {
                    client.client_ajout(request.getParameter("nom"),
                            request.getParameter("prenom"),
                            request.getParameter("adresse"),
                            cp,
                            request.getParameter("ville"),
                            request.getParameter("telephone"),
                            request.getParameter("motdepasse"));
                } catch (ValidationException e) {
                    request.setAttribute("message", "toto à la montagne");
                    return "administration_client_edit";
                } catch (EJBException e) {
                    request.setAttribute("message", "toto à la montagne");
                    return "administration_client_edit";
                }
    Bon mon soucis c'est que mon exception je suis obligé de l'attraper dans le code précédent si je souhaite pouvoir afficher mes erreurs. En fait ce que je souhaite c'est que les "toto à la montagne" représentent mon erreur en disant par exemple "Nom invalide".

    Bref était-il possible à partir d'une erreur qui part de mon JPA pouvoir la retransmettre sous forme d'un String à la place de "toto à la montagne" ? Je peux traiter cela lorsque je reçois les données de la page, mais j'aurai aimé traité l'erreur dans la partie JPA...

  2. #2
    Membre confirmé
    Inscrit en
    Septembre 2006
    Messages
    27
    Détails du profil
    Informations forums :
    Inscription : Septembre 2006
    Messages : 27
    Par défaut
    J'ai peur de ne pas bien comprendre ton problème, mais si ton problème est de mettre dans ta request "nom invalide", alors lorsque tu fais ton catch tu fais un e.getMessage() :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    ...
     
    } catch (ValidationException e) {
                    request.setAttribute("message", e.getMessage());
                    return "administration_client_edit";
    ...

  3. #3
    Membre averti
    Inscrit en
    Septembre 2008
    Messages
    49
    Détails du profil
    Informations forums :
    Inscription : Septembre 2008
    Messages : 49
    Par défaut
    Le problème c'est qu'il ne m'affiche rien si je fait ça. La ou je renseigne "message" c'est une EJBException que j'attrape et non pas une ValidationException... Le problème c'est que cette dernière s'attrape dans mes EJB...

  4. #4
    Inactif  
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    2 189
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : Suisse

    Informations forums :
    Inscription : Mai 2006
    Messages : 2 189
    Par défaut
    pourquoi ne pas faire une validation unique par type d'entité ou tu renverais une liste d'exception appropriée ?

  5. #5
    Membre Expert
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2004
    Messages
    1 184
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Avril 2004
    Messages : 1 184
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    public class ValidationException extends RuntimeException {
     
        public ValidationException(String error) {
            super(error);
        }
    }
    En utilisant ce code tu aura ton message avec getMessage().

    Une citation d'IBM pourrai t'aider :

    How the EJB container handles exceptions

    The EJB container intercepts every method call on the EJB component. As a result, every exception that results in a method call is also intercepted by the EJB container. The EJB specification deals only with handling two types of exception: application exceptions and system exceptions.

    An application exception is defined by the EJB spec as any exception declared on the method signatures in the remote interface (other than RemoteException). An application exception is a special scenario in the business workflow. When this type of exception is thrown, the client is given a recovery option, usually one that entails processing the request in a different way. This does not, however, mean that any unchecked exception declared in the throws clause of a remote-interface method would be treated as an application exception. The spec states clearly that application exceptions should not extend RuntimeException or its subclasses.

    When an application exception occurs, the EJB container doesn't roll back the transaction unless it is asked to do so explicitly, with a call to the setRollbackOnly() method on the associated EJBContext object. In fact, application exceptions are guaranteed to be delivered to the client as is: the EJB container does not wrap or massage the exception in any way.

    A system exception is defined as either a checked exception or an unchecked exception, from which an EJB method cannot recover. When the EJB container intercepts an unchecked exception, it rolls back the transaction and does any necessary cleanup. Then the container wraps the unchecked exception in a RemoteException and throws it to the client. Thus the EJB container presents all unchecked system exceptions to the client as RemoteExceptions (or as a subclass thereof, such as TransactionRolledbackException).

    In the case of a checked exception, the container does not automatically perform the housekeeping described above. To use the EJB container's internal housekeeping, you will have to have your checked exceptions thrown as unchecked exceptions. Whenever a checked system exception (such as a NamingException) occurs, you should throw javax.ejb.EJBException, or a subclass thereof, by wrapping the original exception. Because EJBException itself is an unchecked exception, there is no need to declare it in the throws clause of the method. The EJB container catches the EJBException or its subclass, wraps it in a RemoteException, and throws the RemoteException to the client.

    Although system exceptions are logged by the application server (as mandated by the EJB specification) the logging format will differ from one application server to another. Often, an enterprise will need to run shell/Perl scripts on the generated logs in order to access needed statistics. To ensure a uniform logging format, it is better to log the exceptions in your code.

    Note: The EJB 1.0 spec required that checked system exceptions be thrown as RemoteExceptions. Starting with EJB 1.1, the spec has mandated that EJB implementation classes should not throw RemoteException at all.

  6. #6
    Membre averti
    Inscrit en
    Septembre 2008
    Messages
    49
    Détails du profil
    Informations forums :
    Inscription : Septembre 2008
    Messages : 49
    Par défaut
    Salut.
    Merci pour vous réponses déjà

    Sinon concernant mon problème j'ai fait une solution un peu moins propre que j'espérais mais ça marche.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Récupérer les données à travers JPA
    Par zero.h dans le forum JPA
    Réponses: 7
    Dernier message: 15/08/2012, 18h37
  2. Problème d'ajout JPA sous EJB 3
    Par aymen8219 dans le forum JPA
    Réponses: 2
    Dernier message: 16/08/2011, 04h45
  3. [Exception] Nested exception pour les EJB
    Par R1pToR dans le forum Struts 1
    Réponses: 1
    Dernier message: 05/07/2007, 14h53
  4. Exception au deploiement d'EJB
    Par ChristianVial dans le forum Wildfly/JBoss
    Réponses: 4
    Dernier message: 29/09/2006, 18h07
  5. [EJB Session] class not found exception ?
    Par champion dans le forum Wildfly/JBoss
    Réponses: 4
    Dernier message: 11/02/2005, 23h46

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo