I cannot capture the message I send in my Exception Java Custom

Asked

Viewed 45 times

-1

Everybody, good afternoon, everybody!

I need a help, I am creating some java Apis and I created some custom exceptions, when I invoke the type exection I created: throw new Recursonancontradoexception("Resource not found"); , I get return in Json, without the message field filled : { "timestamp": "2020-12-10T17:04:44.123+00:00", "status": 404, "error": "Not Found", "message": ", "path": "/mkpnumapi/v1/if/1111" }

someone knows how to say why is not capturing the message I send ?

My Class that created the Exception Runtimeexception Exclusion

@ResponseStatus(HttpStatus.NOT_FOUND)
public class RecursoNaoEncontradoException extends RuntimeException {
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;



    public RecursoNaoEncontradoException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    
}


Chamadando a Exception na minha controller

@ApiOperation(value = "Metodo - deletarOfertante", nickname = "deletarOfertante")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK - Request Aceito"),
            @ApiResponse(code = 400, message = "Bad Request - Request ou Parametros Incorretos") })
    @DeleteMapping(value = "/ofertante/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> deletarOfertante(@PathVariable(value = "id") String id) {
        Integer result = service.buscarOfertantePorId(id);
        if (result == 0) {
            throw new RecursoNaoEncontradoException("Recurso inexistente");
        }
        return new ResponseEntity<>(service.excluirOfertante(id), HttpStatus.OK);
    }

Retorno Response:

{ "timestamp": "2020-12-10T17:04:44.123+00:00", "status": 404, "error": "Not Found", "message": ", "path": "/mkpnumapi/v1/if/1111" }

2 answers

0

First, your class needs to match the super class builders of Exception, see example here.

Then, in the class where you want to get the message, you do so:

public class Main {  
    public static void main(String[] args){
        try {
            // Qualquer coisa
            throw new MinhaExcecaoException("Mensagem personalizada.");
        } catch (MinhaExcecaoException e) {
            System.out.println("Mensagem: " + e.getMessage());
          
            /*
             * Isso vai printar:
             *
             * Mensagem: Mensagem personalizada.
             */
        }
    }
}

0

Good night,

follows an example of the form you can use,

First create an Exception class in the style:

public class RecursoNaoEncontradoException extends RuntimeException {
    
    private static final long serialVersionUID = 1L;


    public RecursoNaoEncontradoException(String message) {
        super(message);
    }
}

Later create a Handler to capture the Exception message you played and perform some action:

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RecursoNaoEncontradoHandler {

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    @ExceptionHandler(RecursoNaoEncontradoException.class)
    public ResponseEntity<?> RecursoNaoEncontradoException(RecursoNaoEncontradoException ex) {
        
        HashMap<String, String> message = new HashMap<>();
        
        message.put("Message:", ex.getMessage());
        
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(message);
    }
}

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.