使用@RestControllerAdvice+@ExceptionHandler實(shí)現(xiàn)
也可以使用@ControllerAdvice+@ResponseBody+@ExceptionHandler實(shí)現(xiàn)
創(chuàng)建一個(gè)異常處理的類,放在config包下
?組件類:
package com.dianping.config;
import com.dianping.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class WebExceptionAdvice {
// 捕獲運(yùn)行時(shí)異常
@ExceptionHandler(RuntimeException.class)
public Result handleRuntimeException(RuntimeException e) {
log.error(e.toString(), e);
return Result.fail("服務(wù)器異常");
}
}
?也可以讓不同的異常返回不同的結(jié)果,捕獲什么異常由@ExceptionHandler的value屬性決定,傳入一個(gè)類對(duì)象(可以通過反射獲得)文章來源:http://www.zghlxwxcb.cn/news/detail-617018.html
package com.dianping.config;
import com.dianping.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class WebExceptionAdvice {
// 捕獲運(yùn)行時(shí)異常
@ExceptionHandler(RuntimeException.class)
public Result handleRuntimeException(RuntimeException e) {
log.error(e.toString(), e);
return Result.fail("服務(wù)器異常");
}
// 捕獲空指針異常
@ExceptionHandler({NullPointerException.class})
public Result handleNullPointerException(NullPointerException e) {
return Result.fail("空指針異常");
}
// 捕獲數(shù)字格式異常
@ExceptionHandler({NumberFormatException.class})
public Result handleNumberFormatExcption(NumberFormatException e) {
return Result.fail("數(shù)字格式異常");
}
}
?文章來源地址http://www.zghlxwxcb.cn/news/detail-617018.html
到了這里,關(guān)于springmvc統(tǒng)一異常處理攔截器的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!