google – I cannot conquer code coverage inside Promise “then” and “catch”

I am trying to gain code coverage on my component by implementing a unit test in my spec file, as follows:

home.component.spec.ts

import { HomeService } from './home.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';

import { HomeComponent } from './home.component';
import { of } from 'rxjs';

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;

  // stubs
  const registryStub: HomeComponent = jasmine.createSpyObj('HomeComponent', ('getUserData'));
  const fakeNames = {x: 1};

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: (HttpClientTestingModule),
      declarations: (HomeComponent)
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });


  it('should navigate on promise - success', fakeAsync(() => {

    spyOn(component, 'getUserData').and.returnValue(of(fakeNames));
    (registryStub.getUserData as jasmine.Spy).and.returnValue(Promise.resolve(('test')));
    component.getUserData();

    tick();
    expect(component.getUserData).toHaveBeenCalled();



    // spyOn(component, 'getUserData').and.returnValue(of(fakeNames));
    // component.getUserData().toPromise()
    // .then((data: any) => {
    //   expect(data).toEqual(fakeNames);
    // });




  }));


});

When I run the “ng test –code-coverage” command, I check that the code gap inside the “then” and “catch” blocks are not being covered, as you might see in the illustration below:
code coverage is not being conquered within the red colored area

Could anyone point me to the right direction in order to have a complete code coverage on this component?

By the way, I have a public repo for this:

I look forward to having a reply from you guys

Thanks in advance folks!

clean architecture – Catch “foreign” exception in adapter and convert them in own business exception is a good practice?

I am currently thinking about some design choices regarding exception handling.
My current architecture looks a little like this:

enter image description here

You can see that I have a UI where a try-catch middleware is cathing exceptions like this:

Pseudocode:

catch(CoreUserNotFoundException e)
{
   return 'You provided an invalid user id'
}
catch(CoreToLongException e)
{
   return 'The name is too long'
}
catch(Exception e)
{
   logger.log(e)
   return 'Something went wrong'
}

So only some messages will be returned to the user. All other exceptions are just logged.

Lets say someone wants to add an entity with a user id that has to be validated.
But how do I know weather the user exists or not?
This is done with my business logic. It provides an interface “IUserService” to retrieve a user. The business logic does not care how the app is doing this.
It could get the user via Graph API of Microsoft, or via Auth0 or via Facebook or whatever.
My business logic should work with all kinds of user services.

So in my picture I have a MicrosoftGraph Adapter, that implements the IUserService. This adapter is using my own Graph SDK – this SDK uses the original SDK of Microsoft, but I like my own wrapper and use it in many apps.

In my current design the “MS Graph SDK” throws an Exception if a user does not exist for an id.
This exception is bubbling through my own Graph SDK and caught in the Graph Adapter of my app.

The Graph adapter then transforms this Exception in a CoreUserNotFoundException – the one I am showing to the user:

Pseudocode:

   try {
      user = _userService.getUserById(userId);
   } catch(GraphUserNotFoundException e)
      throw new CoreUserNotFoundException("You provided a bad user id", e);
   }

Of course there are alternative ways:
I could also define an Exception in my Own Graph SDK and re-use this exception through all my projects.
But to show the user a nice message, my UI needed to have a dependency on “Own Graph SDK” because I want to do:

catch(MyOwnGraphSDKUserNotFoundException e)
{
   return 'You provided an invalid user id'
}
catch(Exception e)
{
   logger.log(e)
   return 'Something went wrong'
}

What is probably a bad practice?
In this case I would have to change the UI-code if the Adapter changes, so I am not doing it.

My questions to you:

Was my design choice correct? Or does it seem unprofessional to you?
I am still learning about clean architectures, hexagonal architectures etc., but didnt read too much about Exception handling in this topic.

reverse proxy – Why “/” nginx location rule fails to catch some URLs? Isn’t it supposed to go with all?

I have an nginx that serves as reverse proxy, and it redirects requests to an angular app or to a node js backend app depending on the request URL. There is also a rule location ~ /s/(cas)/(.*) that serves static content (although I’m seeing now that if “/” caught this route too, it would not be necessary to have that rule, as static content is also kept at backend:4000).

My concern is particular to the most general rule “/” that is supposed to catch all requests that did not fall into any other location, it is not applying correctly to some URLS causing nginx to send its 50x.html error page. In particular, my problem is that this redirection seems to not catch all traffic that didn’t fit a previous rule. And is the one rule in charge of redirecting the traffic that should land on the angular app.

If I’m correct, this should fall under the “/” rule:

https://SUBDOMAIN.DOMAIN.es/user/trip/13925/instant?sharedToken=(REDACTED)

And these should at least be redirected correctly by the “/” rule, but also show the nginx fail page after a lot of timeout:

https://SUBDOMAIN.DOMAIN.es/user/trip/foo/instant?sharedToken=(REDACTED) # changed id for "foo"
https://SUBDOMAIN.DOMAIN.es/user/trip/instant?sharedToken=(REDACTED) # removed id segment of url
https://SUBDOMAIN.DOMAIN.es/user/instant?sharedToken=(REDACTED) # also removed "trip" segment of url

Any other variation of the url works fine and is redirected to https://backend:4000.

So, why aren’t these rules caught by the location “/”?

This is the nginx config file. Domain and subdomain have been omitted on purpose:

server {
    listen 443 ssl http2;
    listen (::):443 ssl http2;
    expires $expires;
    add_header Strict-Transport-Security "max-age=15768000; includeSubDomains" always;
    server_name (SUBDOMAIN).(DOMAIN_NAME).es;
    ssl_certificate /etc/nginx/ssl/CERT.crt;
    ssl_certificate_key /etc/nginx/ssl/CERT.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
    ssl_session_cache shared:SSL:5m;
    ssl_session_timeout 1h;
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_min_length 256;
    gzip_types text/plain text/css application/javascript application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;

    location ~ /api(?<url>/.*)  {
        resolver 127.0.0.11;
        set $target http://backend:5000/api${url}$is_args$args;
        proxy_set_header X-Forwarded-Host $host;     # Relay whatever hostname was received
        proxy_set_header X-Forwarded-Proto $scheme;  # Relay either http or https
        proxy_set_header X-Forwarded-Server $host;   # Relay whatever hostname was received
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Prefix /api/;
        proxy_set_header Host "SUBDOMAIN.DOMAIN.es";

        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Max-Age 3600;
        add_header Access-Control-Expose-Headers Content-Length;
        add_header Access-Control-Allow-Headers Range;

    ## Websockets support 2/2
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    ## END Websockets support 2/2

        proxy_pass $target;
        client_max_body_size 10M;
    }

    location ^~ /_assets/ {
        alias /usr/share/nginx/html/assets/;
    }

    location ^~ /.well-known/acme-challenge/ {
        alias /usr/share/nginx/html/.well-known/acme-challenge/;
    }

    location ~ /s/(cas)/(.*) {
        add_header Pragma "no-cache";
        add_header Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
        proxy_pass http://backend:4000;
    }

    location / {
        #root /usr/share/nginx/html;
        proxy_pass http://backend:4000;
        expires -1;
        proxy_set_header X-Forwarded-Host "SUBDOMAIN.DOMAIN.es";
        proxy_set_header X-Forwarded-Server "SUBDOMAIN.DOMAIN.es";
        proxy_set_header Host "SUBDOMAIN.DOMAIN.es";

        add_header Pragma "no-cache";
        add_header Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";

        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Max-Age 3600;
        add_header Access-Control-Expose-Headers Content-Length;
        add_header Access-Control-Allow-Headers Range;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

java – Unreachable catch block for PSQLException. This exception is never thrown from the try statement body

Estoy intentando que me pille la excepcion PSQLException sin embargo me dice que no se puede llegar a este bloque , alguien sabe por qué? Osea no llego a ejecutar ni nada , Eclipse me lo marca como un error.
Sin embargo si yo por ejemplo pongo Exception e , en vez de PSQLException e , no da error..

@DeleteMapping("/delete/{pais_id}")
    public Resultado<Pais> eliminaPais(@PathVariable("pais_id") Long pais_id, HttpServletResponse response) {
        Resultado<Pais> res = new Resultado<>();
    
        try {
            Optional<Pais> existePais = paisService.getFindById(pais_id);
            if (existePais.isPresent()) {
                if (pais_id != null) {
                    // monedaService.setANullPais(pais_id);
                    try{
                        paisService.getEliminaPais(pais_id);
                    res.setCodigo(200);
                    res.setMensaje("El país " + existePais.get().getNombre() + " ha sido eliminado");
                    res.setDatos(existePais.get());
                    }catch(PSQLException e) { //HERE 
                        res.setCodigo(400);
                        res.setMensaje("El país no " + existePais.get().getNombre() + " ha sido eliminado");
                        res.setDatos(null);
                    }
                    
                    
                    
    
                }
            } else {
                res.setSuccess(false);
                res.setMensaje("Se ha producido un error, el ID proporcionado no existe " + pais_id);
                res.setCodigo(400);
            }
        } catch (Exception e) {
        
            res.setSuccess(false);
            res.setMensaje("Se ha producido un error: " + e.getMessage());
            res.setCodigo(400);
        }
        response.setStatus(res.getCodigo());
        return res;
    }

seo – How to catch the search query when the user comes from a search engine to the web site?

Passing the originating search query to the destination website was a feature discontinued by Google (and other search engines followed suit) almost a decade ago.

If you’re running Ads, then yes (although they’ve starting hiding some of that in certain situations). That is possible. But it’s not available for organic search.

php – Should i throw exceptions in the service layer or repository, and catch it on the controller?

I read some answers here on stack exchange, but none really “hits the nail on the head” about where to throw exceptions, where I shouldn’t and where to catch them.

the idea that an exception should be thrown in exceptional cases is very vague, for example, if I can’t find a user in my data source (repository) I can’t continue the flow of my code, can this be considered exceptional?

I also understand that there are caveats about flow control with exceptions, for me it does not seem right to use try/catch within the service, to catch all the exceptions that a repository/adapter/whatever may throw to control what to do next.

based on this, a code example with a “service” and a controller calling the service and catching all of the service exceptions:

Service:

class CheckUserUltraSecretInformation
{

    public function __construct(
        private CachedUserDataRepository $cachedDataRepository,
    )
    {
    }

    public function handle(string $document)
    {
        $cachedUserData = $this->cachedDataRepository->findByDocument($document);

        if (empty($cachedUserData)) {
            throw new CachedUserDataNotFoundException('User Cached information not found, cannot proceed');
        }

        if ($cachedUserData->hasExpired()) {
            throw new CachedUserDataHasExpiredException('Cached user data is expired');
        }
        // return ultra secret information
    }
}

Controller:

class UserSecretInformationController
{

    public function __construct(
        private CheckUserUltraSecretInformation $checkUserUltraSecretInformation)
    {
    }

    public function checkUserInformation(Request $request)
    {
        $document = $request->input('document');

        try {
            $userUltraSecretInformation = $this->checkUserUltraSecretInformation->handle($document);
        } catch (CachedUserDataNotFoundException $exception) {

            // return json response with http code 400

        } catch (CachedUserDataExpiredException $exception) {
            //returns json response with http code 500
        }
    }
}
  • Is it “correct” that my repository does not throw exceptions, and only returns null/false when it cannot return an entity? if not, what is the problem?

  • if my repository throws exceptions, should my service capture them and re-launch them as service exceptions? is this considered flow control?

  • Are the outer layers the “most correct” to capture and handle exceptions? in my example the controller is used, can It know the name of the services/use-cases exceptions?

What is the catch here?

I just saw an offer on SSDnodes offering 32GB RAM 640GB NVMe 8 vCPU for $89/year and 48GB RAM 720GB NVMe 12 vCPU for $99/year

It looks to… | Read the rest of https://www.webhostingtalk.com/showthread.php?t=1843128&goto=newpost

dnd 5e – Can a high level Archer/Ranger catch an arrow fired at them?

Let’s say a highly skilled level 15 archer of whatever flavour is shot at by an enemy archer. Without using the gloves of missile snaring, could you have your archer use his reaction to catch the arrow?? Especially if the enemy archers shot misses your AC. I would expect some sort of Dex or Dex save for that.

plugins – }catch (ex){} showing in header

I have this string showing in the header of my site :
}catch (ex){}

I can see this in the source code :

    }</style><script>try{ <script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)(0),m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","https://chimpstatic.com/mcjs-connected/js/users/2095bd42340716fa509260a90/406ca4747992260e47dbadffd.js");</script>
 }catch (ex){}</script>     <style type="text/css" id="wp-custom-css">
            @media (max-width: 465px){
    .heading-mobile-center{
        text-align: center;
    }

Can anyone help ?

Thanks.

rest – Best way to trigger javascript error to go to catch block

I have a couple of doubts regarding the quality of my code. I’m working on a helper function (for KoaJS) where I’m validating a Firebase ID token. If it is valid, I return the decoded token; otherwise I return an authorization error.

Also, if the function is initialized to request email to be verified, it will check if email of Firebase account is already verified. If there’s an authorization error (token has expired, token is invalid, etc), it returns an error with the property codePrefix equals to auth. I use that to verify if it is an authorization error or any other kind of error.

validateIDToken: function (emailValidated = false) {

    return async (request) => {

        const { idtoken } = request.headers;

        try {
            const decodedToken = await firebaseApp.auth().verifyIdToken(idtoken);
            if (emailValidated && !decodedToken.emailValidated) {
                throw { codePrefix: 'auth' };
            }

            return decodedToken;
        }
        catch (err) {
            if (err.codePrefix === 'auth') {
                throw Boom.unauthorized();
            }

            throw Boom.badImplementation('Error validating ID Token');
        }
    };
}

My doubts are:

  • Is it correct to return a JSON with codePrefix property to manually throw an error and go to the catch clause? Do you think it is a better/more elegant way to do it?
  • Is it correct to not having a default return statement, but to rely that it will return something in the normal flow or in the catch clause? I don’t want to fall in the scenario of having multiple return/throw clauses in a single function.
  • Do you think it is ok to default catch clause to throw a 500 error (missing a logger error statement)?