@RestControllerAdvice unified exception handling

GlobalExceptionHandler unified exception handling class, MyException custom exception class,
@RestControllerAdvice equivalent to the Controller section, abnormal centrally, customization, it's better to return to the front.
@RestControllerAdvice
public class GlobalExceptionHandler {
    public GlobalExceptionHandler(){}
    @ExceptionHandler({MyException.class})
    public ResponseEntity<ResErr> handleMyException(MyException ex){
        ResErr resErr=new ResErr();
        resErr.setErrCode(12344);
        resErr.setErrMsg(ex.getMessage());
        return new ResponseEntity<>(resErr, HttpStatus.OK);
    }
    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<ResErr> handleMyException(RuntimeException ex){
        ResErr resErr=new ResErr();
        resErr.setErrCode(99999);
        resErr.setErrMsg ( "runtime exception" );
         return  new new ResponseEntity <> (resErr, HttpStatus.OK);
    }
    @ExceptionHandler({Exception.class})
    public ResponseEntity<ResErr> handleMyException(Exception ex){
        ResErr resErr=new ResErr();
        resErr.setErrCode(99999);
        resErr.setErrMsg ( "system exceptions" );
         return  new new ResponseEntity <> (resErr, HttpStatus.OK);
    }
}

 

Guess you like

Origin www.cnblogs.com/mufeng07/p/12659441.html