博客
关于我
SpringBoot全局统一异常处理(包含404错误处理)
阅读量:342 次
发布时间:2019-03-04

本文共 1768 字,大约阅读时间需要 5 分钟。

SpringBoot全局统一异常处理(包含404错误处理)

1.ControllerAdvice&&ExceptionHandler处理异常

package com.lius.controllers;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/exception")public class testExceptionColtroller {	@RequestMapping("/nullException")	public String nullException() {		//触发空指针异常		throw new NullPointerException("空指针异常!");	}}
package com.lius.handler;import java.util.HashMap;import java.util.Map;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvice(basePackages = "com.lius.controllers")public class handlerException {	@ExceptionHandler(NullPointerException.class)	@ResponseBody	private Map
handlerNullPointException(){ Map
map = new HashMap<>(); map.put("code", 500); map.put("message", "代码错误,空指针异常!"); return map; }}

 

2.ErrorController拦截处理404异常

package com.lius.controllers;import java.util.HashMap;import java.util.Map;import org.springframework.boot.web.servlet.error.ErrorController;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;/** * 

处理404等error错误

* @author lius * */@Controllerpublic class errorController implements ErrorController { @Override public String getErrorPath() { // TODO Auto-generated method stub return "/error"; } @RequestMapping("/error") @ResponseBody public Map
handlerError(){ Map
errMap = new HashMap<>(); errMap.put("code", 404); errMap.put("message", "404页面未找到!"); return errMap; }}

 

转载地址:http://innq.baihongyu.com/

你可能感兴趣的文章
Netty工作笔记0051---Netty核心模块2
查看>>
Netty工作笔记0052---Pipeline组件剖析
查看>>
Netty工作笔记0053---Netty核心模块梳理
查看>>
Netty工作笔记0054---EventLoop组件
查看>>
Netty工作笔记0055---Unpooled应用实例1
查看>>
Netty工作笔记0056---Unpooled应用实例2
查看>>
Netty工作笔记0057---Netty群聊系统服务端
查看>>
Netty工作笔记0058---Netty群聊系统客户端
查看>>
Netty工作笔记0059---Netty私聊实现思路
查看>>
Netty工作笔记0060---Netty心跳机制实例
查看>>
Netty工作笔记0060---Tcp长连接和短连接_Http长连接和短连接_UDP长连接和短连接
查看>>
Netty工作笔记0061---Netty心跳处理器编写
查看>>
Netty工作笔记0062---WebSocket长连接开发
查看>>
Netty工作笔记0063---WebSocket长连接开发2
查看>>
vue样式穿透 ::v-deep的具体使用
查看>>
Netty工作笔记0065---WebSocket长连接开发4
查看>>
Netty工作笔记0066---Netty核心模块内容梳理
查看>>
Vue基本使用---vue工作笔记0002
查看>>
Netty工作笔记0068---Protobuf机制简述
查看>>
Netty工作笔记0069---Protobuf使用案例
查看>>