Custom Exception in Sprin Boot

I have written the below Custom Error Handler in SPRING BOOT

@RestControllerAdvice 
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler
   // @ResponseBody
    public ResponseEntity<CustomErrorResponse> customHandleNotFound(Exception ex, WebRequest request) {

        CustomErrorResponse errors = new CustomErrorResponse();
        errors.setTimestamp(LocalDateTime.now());
        errors.setError(ex.getMessage());
        errors.setStatus(HttpStatus.CONFLICT.value());
        errors.setErrorMsg(errors.getErrorMsg());

        return  ResponseEntity.ok(errors);

    }

Below is my code Controller method

@RestController
@RequestMapping(value="/api")
public class AppController {




   @Autowired
    private UserRepository userRepository;



      @RequestMapping(value="/home/{id1}" ,method=RequestMethod.PUT)
     @ResponseBody
      public String home(@PathVariable("id1") Long idValue,    @RequestBody @Valid Student s)
    {

         System.out.println( " idValue is  "  + idValue);

        System.out.println( " Student -->" + s.getName()  + " -- "  + s.getId());


      return    "job done";

    }



      @RequestMapping("/foos")
    //  @ResponseBody
      public String getFoos(@RequestParam(value="t1",required=true)  String id)  {

          int i =1/0;

          System.out.println(" id is " + i++);
            return "ID: " + id + "  status: Success";
      }

The exception handler is working fine for the method getFoos()
when it encounters 1/0 I get the output in POSTMAN as which is as expected

{
    "timestamp": "2019-08-04 11:24:22",
    "status": 409,
    "error": "/ by zero",
    "errorMsg": "ERROR-msg"
}

But in my home() method I deliberately made Student object as invalid and I get no error message in POSTMAN but just in the eclipse console.
Why?

I get this message.So how do I kick in CustomGlobalExceptionHandler when the Student object is invalid

2019-08-04 23:25:57.551 WARN 9652 — [nio-8080-exec-6]
.m.m.a.ExceptionHandlerExceptionResolver : Resolved
[org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing: public java.lang.String
com.example.hibernatemapping.controller.AppController.home(java.lang.Long,com.example.hibernatemapping.domain.Student)]

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Well, there are many things to say. First, exception handlers take an exception class as parameter, which allow you to return other errors following the exception class you throw in a controller method. The one you wrote catch all exceptions and return the same error model, which is not a right idea. The right way to do is to write an abstract class AbstractMyAppException that extends Exception, and then implement a new class that extends of it for every error case you have. Then, add two @ExceptionHandler : One bind on the AbstractMyAppException class that return all errors that your… Read more »

Jason
Guest

I solved it by adding the below in my ControllerAdviceI will just change the code to map error to my custom Pojo class CustomErrorResponse @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { Map<String, Object> body = new LinkedHashMap<>(); body.put("timestamp", new Date()); body.put("status", status.value()); //Get all errors List<String> errors = ex.getBindingResult() .getFieldErrors() .stream() .map(x -> x.getDefaultMessage()) .collect(Collectors.toList()); body.put("errors", errors); System.out.println( " erro here "); return new ResponseEntity<>(body, headers, status); }