Springboot2.0處理自定義異常并返回json
這篇文章主要介紹了Springboot2.0處理自定義異常并返回json,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
1. 編寫自定義異常類
package cn.jfjb.crud.exception;
/**
* @author john
* @date 2019/11/24 - 9:48
*/
public class UserNotExistException extends RuntimeException {
public UserNotExistException() {
super("用戶不存在");
}
}
2. 處理自測試異常
package cn.jfjb.crud.handler;
import cn.jfjb.crud.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* @author john
* @date 2019/11/24 - 10:43
*/
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map<String, Object> handleException(Exception e) {
Map<String, Object> map = new HashMap<>();
map.put("code", "user.notexist");
map.put("message", e.getMessage());
return map;
}
}
3. 配置application.yml文件(不配置的話無法獲取exception)
server: error: include-exception: true
4. 編寫測試
package cn.jfjb.crud.controller;
import cn.jfjb.crud.exception.UserNotExistException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author john
* @date 2019/11/22 - 19:38
*/
@Controller
public class HelloController {
@RequestMapping({"/testException"})
public String testException(@RequestParam("user") String user) {
if (user != "aaa") {
throw new UserNotExistException();
}
return "index";
}
}


以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot使用Feign進(jìn)行服務(wù)間通信的實現(xiàn)示例代碼
Feign是一個開源的Java HTTP客戶端,可以幫助我們在SpringBoot應(yīng)用中快速構(gòu)建和使用HTTP客戶端,方便實現(xiàn)服務(wù)間的通信,本文就來介紹一下SpringBoot使用Feign進(jìn)行服務(wù)間通信的實現(xiàn)示例代碼,感興趣的可以了解一下2024-01-01
詳解Spring cloud使用Ribbon進(jìn)行Restful請求
這篇文章主要介紹了詳解Spring cloud使用Ribbon進(jìn)行Restful請求,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
淺析Spring Boot單體應(yīng)用熔斷技術(shù)的使用
這篇文章主要介紹了淺析Spring Boot單體應(yīng)用熔斷技術(shù)的使用,幫助大家更好的理解和使用spirngboot框架,感興趣的朋友可以了解下2021-01-01
Delegate IDE build/run actions to maven 配置會影響程序運行嗎?
這篇文章主要介紹了Delegate IDE build/run actions to maven 配置會影響程序運行嗎,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08

