SpringMVC中@RestControllerAdvice統一異常處理


GlobalExceptionHandler為統一異常處理類,MyException自定義異常類,
@RestControllerAdvice相當於Controller的切面,對異常統一處理,定制,這樣更好返回給前端。
@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("運行時異常");
        return new ResponseEntity<>(resErr, HttpStatus.OK);
    }
    @ExceptionHandler({Exception.class})
    public ResponseEntity<ResErr> handleMyException(Exception ex){
        ResErr resErr=new ResErr();
        resErr.setErrCode(99999);
        resErr.setErrMsg("系統異常");
        return new ResponseEntity<>(resErr, HttpStatus.OK);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM